Ask your JavaScript questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

javascript PDO to populate a mariadb database table with these variable values. JavaScript

  • SOLVED

I have a web page https://verlager.com/ with multiple input fields.

Like: P1, P2, P3, ... P50

sample: <input id = "P1">Jones, Jim</input>
<input id = "P2">Smith, Paul</input>
...

I want to use php or javascript PDO to populate a mariadb database "cccr" table "account" with these values.

Like $conn->exec("INSERT INTO account (P1) VALUES (" .$P1 ")";

Can you help? I'll need a while loop, since I don't want to write out 50 variables 6 times.

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "cccr";


try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception

$P1 = $_GET["P1"]; $P2 = $_GET["P2"]; $P3 = $_GET["P3"];

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


// begin the transaction
$conn->beginTransaction();

$conn->exec("INSERT INTO account (P1) VALUES (" .$P1 ")";


);

// commit the transaction
$conn->commit();
echo "New records created successfully";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}

$conn = null;

?>

Answers (1)

2019-05-13

Rainner Lins answers:

Here's some quick PHP code I put together, the variables at the top are for my setup here, make sure to update them for yours when running it.

https://gist.github.com/rainner/6c474e499a348740a94d53ce54dfe53a

The code is working for me here on my local setup running PHP version 5.6.5.

It works by detecting when the form has been POSTED and mapping the same input names to the column names for the table (account) in the database.

Also note that it uses prepared statements when inserting data to the database to help protect against SQL injection attacks. You can read a little about prepared statements here in the PHP manual site:

https://www.php.net/manual/en/pdo.prepared-statements.php