Problem converting mysqli to PDO | PHP mySQL - php

I am currently converting my mySQLi PHP code into PDO for better security and I am having some trouble understanding how I can convert the code below and implement it into my new PDO PHP
The code below should take the last inserted ID (the one the PDO is inserting) and set the column idnum equal to the NUM(and the last inserted id).
How can this be converted and added to the PDO?
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$sql = "UPDATE Equipment SET idnum = CONCAT('NUM', '$last_id') WHERE equipment_id = '$last_id'";
mysqli_query($conn, $sql);
echo "New record created successfully. Last inserted ID is: " . last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
I would like to add the code to the following PDO PHP script:
$hostdb = 'localhost';
$namedb = 'dbname';
$userdb = 'userdb';
$passdb = 'passdb';
$charset = 'utf8';
if (isset($_POST['name'], $_POST['place'], $_POST['person'] , $_POST['number'] , $_POST['other_name'])) {
// Connect and create the PDO object
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:host=$hostdb;dbname=$namedb;charset=$charset", $userdb, $passdb, $options);
$stmt = $conn->prepare( ' INSERT INTO `Table1` (name, place, person, number, other_name, progress)
VALUES (:name,:place,:person,:number,:other_name, "Done") ' );
$stmt->execute([
'name' => $_POST['name'],
'place' => $_POST['place'],
'person' => $_POST['person'],
'number' => $_POST['number'],
'other_name' => $_POST['other_name'],
]);
// Shows the number of affected rows
echo 'Affected rows : '. $stmt->rowCount();
}

Like this I guess (if you want them combined):
$hostdb = 'localhost';
$namedb = 'dbname';
$userdb = 'userdb';
$passdb = 'passdb';
$charset = 'utf8';
if (isset($_POST['name'], $_POST['place'], $_POST['person'] , $_POST['number'] , $_POST['other_name'] )) {
// Connect and create the PDO object
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:host=$hostdb;dbname=$namedb;charset=$charset", $userdb, $passdb, $options);
try{
//start a transaction {ACID}
$conn->beginTransaction();
$stmt = $conn->prepare('INSERT INTO `Table1` (`name`, `place`, `person`, `number`, `other_name`, `progress`)
VALUES (:name,:place,:person,:number,:other_name, "Done") ' );
$stmt->execute([
'name' => $_POST['name'],
'place' => $_POST['place'],
'person' => $_POST['person'],
'number' => $_POST['number'],
'other_name' => $_POST['other_name'],
]);
//get the last insert ID
$last_id = $conn->lastInsertId();
$stmt = $conn->prepare('UPDATE `Equipment` SET `idnum` = CONCAT("NUM", :last_id_0) WHERE `equipment_id` = :last_id_1');
//named placeholders must be unique
$stmt->execute([
'last_id_0' => $last_id,
'last_id_1' => $last_id
]);
echo "New record created successfully. Last inserted ID is: " . $last_id;
//commit the changes
$conn->commit();
}catch(PDOException $e){
//roll back the changes on errors
$conn->rollback();
echo $e->getMessage();
}
// Shows the number of affected rows this is pointless (for insert 1 row it's always 1 or an error)
//echo 'Affected rows : '. $stmt->rowCount();
}
Transactions are like changing the DB for pretend (if it's INNODB table), then if there is an error with one of the query both fail.
It's advisable to use them when creating related records that way you don't leave orphan records or rows without the relationship just hanging around.

Related

sqlite to mysql using php

I have an application that writes it's data to SQLite everyday. I now want to upload this data into my webhost to use. So I have a scheduled sFTP script to upload the .sqlite file to my webhost and then run another scheduled task to run the php code.
I know that I can use SQLite with PDO but all my other data on the host is in MySQL, so I want to keep everything in the MySQL format.
I have tried writing some php code that will read the sqlite file via PDO and then insert into the MySQL table again with PDO. The script will hopefully run on multiple tables to import so using foreach with Key/Values so I do not have to hardcode every single column in each table (about 30 columns per table)
However I have tried various things but just can not seem to find why the above code does not work problem so asking for help from much better minded users. Please view my code.
Thanks
<?php
ini_set('max_execution_time', 480); //480 seconds = 8 minutes
try {
// Connect to MySQL database
$host = '127.0.0.1';
$db = 'coredb';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdomysql = new PDO($dsn, $user, $pass, $opt);
// Connect to SQLite database in file
$file_db = new PDO('sqlite:frp.sqlite');
$file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * from frp_teamdata';
$stmt = $file_db->prepare($sql);
$stmt->execute();
$sqliteresults = $stmt->fetch(PDO::FETCH_ASSOC);
foreach($sqliteresults as $results){
foreach($results as $key => $value){
$stmt = $pdomysql ->prepare("INSERT INTO frp_teamdata (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $key);
$stmt->bindParam(':value', $value);
$stmt->execute();
}
}
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
Give this a try:
<?php
ini_set('max_execution_time', 480); //480 seconds = 8 minutes
try {
// Connect to MySQL database
$host = '127.0.0.1';
$db = 'coredb';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdomysql = new PDO($dsn, $user, $pass, $opt);
// Connect to SQLite database in file
$file_db = new PDO('sqlite:frp.sqlite');
$file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * from frp_teamdata';
$stmt = $file_db->prepare($sql);
$stmt->execute();
$sqliteresults = $stmt->fetch(PDO::FETCH_ASSOC);
//Prepare the statement only once!
$stmtmysql = $pdomysql ->prepare("INSERT INTO frp_teamdata (name, value) VALUES (:name, :value)");
//Bind the params only once -- I assume the keys and values are strings
$stmtmysql->bindParam(':name', $key, PDO::PARAM_STR);
$stmtmysql->bindParam(':value', $value, PDO::PARAM_STR);
foreach($sqliteresults as $results){
foreach($results as $key => $value){
$stmtmysql->execute();
}
}
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
Note: I have not tried the code, so let me know if you have any issues.

insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048

Thank you for being here!
i want to be able to select acc_id from account_info table and insert it in patient_info table as Foreign Key
I am getting this error :
In my localhost i can see the value it's suppose to return.
And this error which I suppose it occurs because i haven't inserted acc_id yet SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acc_id' cannot be null
Also var_dump($data) returns array(1) { [0]=> object(stdClass)#3 (1) { ["acc_id"]=> int(124) } }
php file :
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$data = array();
try{
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
// Return data as JSON
echo json_encode($data);
var_dump($data);
$sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
VALUES(:data, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
$stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
$stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
$stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
$stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
$stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
$stmt->bindParam(':data', $acc_id, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record was added to the database'));
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It seems there are multiple issues in your code or the way you are trying to do things. Please check the code below. It should work. I have added few inline comments. Please check them:
<?php
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$data = array();
try {
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
// You do not need to return response from here
// echo json_encode($data);
// var_dump($data);
$sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";
$stmt = $pdo->prepare($sql);
// the $p_fname, $p_lname, $p_gender etc variables in your code were never initiated. You would get
// notice for this if you had all error_reporting on. I am not sure from where you intend to get this info;
// so, I just added some dummy data.
$p_fname = 'Patient first name';
$p_lname = 'Patient last name';
$p_gender = 'm';
$p_condition = 'condition';
$p_birthdate = '1999-01-01';
$p_emergencycontact = 'Contact';
$stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
$stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
$stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
$stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
$stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
$stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
// You do not have any $acc_id variable in your code. To get data from your fetch you need to do
// like this:
$stmt->bindParam(':acc_id', $data[0]->acc_id, PDO::PARAM_STR);
$stmt->execute();
header('Access-Control-Allow-Origin: *');
// If you want to get the acc_id in your client side through the AJAX call, combine both
// mesage and data in the same JSON object.
echo json_encode(
array(
'message' => 'Congratulations the record was added to the database'
'data' => $data
)
);
} catch(PDOException $e) {
// make sure to send the proper status code
http_response_code(500);
// even error should be sent back as in json so that your javascript client can
// easily parse it
echo json_encode(
array(
'error' => $e->getMessage()
)
);
}
?>

Insert Selected data in database

Basically I want to insert a Foreign key acc_id in patient_info table from account_info table.
I have managed to retrieve the data from my database. Now I want to insert it in another table as Foreign key. I have following code :
try {
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
How can I insert the value in the table?
this is the full code :
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'root';
$pwd = '';
$db = 'ringabell';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$key = strip_tags($_REQUEST['key']);
$data = array();
switch($key)
{
// Add a new record to the technologies table
case "create":
// Sanitise URL supplied value
$acc_id = filter_var($_REQUEST['acc_id'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_fname = filter_var($_REQUEST['p_fname'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_lname = filter_var($_REQUEST['p_lname'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_gender = filter_var($_REQUEST['p_gender'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_condition = filter_var($_REQUEST['p_condition'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_emergencycontact = filter_var($_REQUEST['p_emergencycontact'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$p_birthdate = filter_var($_REQUEST['p_birthdate'],
FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
try{
$stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
$sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
$stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
$stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
$stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
$stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
$stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
$stmt->bindParam(':acc_id', $acc_id, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record was added to the database'));
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
}
?>
I am getting this error:
ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
I am getting the error here which links back to the php file:
load()
{
this.http.get('http://localhost:10080/ionic/patients.php')
.map(res => res.json())
.subscribe(data =>
{
this.items = data;
});
}
Solution: insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048
I'm pretty sure you could improve your code by removing your while loop and instead go like :
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
Are you sure you're getting expected JSON (tried any var_dump of $data before printing it ?) ?
Isn't it just a simple problem with JavaScript ? Have you tried to use the data you're supposed to get in your JavaScript part ?
It might be a problem of setting headers inside your XMLHttpRequest, and JavaScript doesn't care and give you the JSON anyway...
Now obvious questions :
I can't see where you connect to your database. Are you connected ?
You're trying to insert an ID, does MySQL allow you to INSERT auto increment value ? (in which case, isn't acc_id an Int ?)
You're sending values through $_REQUEST, are you sure you're getting anything through $_REQUEST (btw, check $_GET and $_POST)
I hope it helps

"NOTICE: Object of class PDOStatement could not be converted to int" during insert operation

My code is working, but there is a NOTICE on the if satement while running. I tried to solve it, but I can't.
Notice error: Notice: Object of class PDOStatement could not be converted to int in D:\wamp\www\pdo\addOrders.php on line 30
here is my code:
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'root';
$password = '';
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
/* echo "Connected to $dbname at $host successfully.<br/>"; */
}
catch (PDOException $e)
{
echo "<h3>Error:</h3>". $e->getMessage();
}
$customer_id=addslashes($_GET['customer_id']);
$t=time();
$d=date("Y-m-d",$t);
$sql= "INSERT INTO `test`.`orders` (`customer_id`, `date`) VALUES ('$customer_id', '$d');";
$result =$conn->query($sql);
$lastid = $conn->lastInsertId();
if($result==1)
{
$query = "select * from `orders` where customer_id='$customer_id'";
$result = $conn->query($query);
$dbvalue = $result->fetch(PDO::FETCH_OBJ);
$customer_id=$dbvalue->customer_id;
$date=$dbvalue->date;
$details = array(
'status'=>'sucess',
'message'=>'customer added sucessfully',
'id' => $lastid,
'customer_id' => $customer_id,
'date' => $date,
);
echo json_encode($details);
}
else
{
$detail = array(
'status'=>'unsucess',
'message'=>'cannot add customer',
);
echo json_encode($detail);
}
?>
$conn->query($sql) returns either a PDOStatement object upon success, or false on failure. Comparing either to == 1 is nonsense. It was nonsense in the times of mysql_query, and is still nonsense in the times of PDO. You want to test the result for truthiness, not against a numeral.
It's as simple as:
if ($result)

PHP PDO Insert Using Loop

I am having trouble using PDO to insert multiple records into a database. I can successfully add a single record, but as soon as I add the foreach loop, it fails. After reading a number of other SO questions regarding this, I believe I need to "bind" my variables, although I am completely confused on the proper syntax.
Here is the original function I created:
<? function addToDatabase () {
//Get All Variables
$timestamp = date("Y-m-d H:i:s");
$schoolName = $_SESSION['schoolName'];
$schoolStreet = $_SESSION['schoolStreet'];
$schoolCity = $_SESSION['schoolCity'];
$schoolState = $_SESSION['schoolState'];
$schoolZip = $_SESSION['schoolZip'];
$schoolContactName = $_SESSION['schoolContactName'];
$schoolContactTitle = $_SESSION['schoolContactTitle'];
$schoolContactPhone = $_SESSION['schoolContactPhone'];
$schoolCsontactEmail = $_SESSION['schoolContactEmail'];
$inputMethod = $_SESSION['inputMethod'];
$studentDataArray = $_SESSION['studentDataArray'];
$studentFirstNameField = $_SESSION['studentFirstNameField'];
$studentLastNameField = $_SESSION['studentLastNameField'];
$studentStreetField = $_SESSION['studentStreetField'];
$studentCityField = $_SESSION['studentCityField'];
$studentStateField = $_SESSION['studentStateField'];
$studentZipcodeField = $_SESSION['studentZipcodeField'];
$studentDOBField = $_SESSION['studentDOBField'];
$studentGenderField = $_SESSION['studentGenderField'];
$studentGradeField = $_SESSION['studentGradeField'];
//Connnect to Database
$host = 'myHost';
$un = 'myUsername';
$pw = 'myPassword';
$db_name = 'myTable';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbName", $un, $pw);
echo 'Connected to database<br>';
$sql = "INSERT INTO studentData (originallyAddedOn, inputMethod, studentFirst, studentLast, studentStreet, studentCity, studentState, studentZip, studentDOB, studentGender, studentGrade, schoolName, schoolStreet, schoolCity, schoolState, schoolZip, schoolContactName, schoolContactTitle, schoolContactEmail, schoolContactPhone) VALUES (:originallyAddedOn, :inputMethod, :studentFirst, :studentLast, :studentStreet, :studentCity, :studentState, :studentZip, :studentDOB, :studentGender, :studentGrade, :schoolName, :schoolStreet, :schoolCity, :schoolState, :schoolZip, :schoolContactName, :schoolContactTitle, :schoolContactEmail, :schoolContactPhone)";
foreach ($studentDataArray as $student){
$q = $conn->prepare($sql);
echo $student[$studentFirstNameField]."<br>";
$q->execute(array( ':originallyAddedOn'=>$timestamp,
':inputMethod'=>$inputMethod,
':studentFirst'=>$student[$studentFirstNameField],
':studentLast'=>$student[$studentLastNameField],
':studentStreet'=>$student[$studentStreetField],
':studentCity'=>$student[$studentCityField],
':studentState'=>$student[$studentStateField],
':studentZip'=>$student[$studentZipField],
':studentDOB'=>$student[$studentDOBField],
':studentGender'=>$student[$studentGenderField],
':studentGrade'=>$student[$studentGradeField],
':schoolName'=>$schoolName,
':schoolStreet'=>$schoolStreet,
':schoolCity'=>$schoolCity,
':schoolState'=>$schoolState,
':schoolZip'=>$schoolZip,
':schoolContactName'=>$schoolContactName,
':schoolContactTitle'=>$schoolContactTitle,
':schoolContactEmail'=>$schoolContactEmail,
':schoolContactPhone'=>$schoolContactPhone));
}
// close the database connection
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
The $studentDataArray looks similar to this:
0 => //student 1
array
[0] => 'Joe' //First
[1] => 'Smith' //Last
[2] => '101 Main St' //Street
[3] => 'Boston' //City
[4] => 'MA' //State
[5] => '01234' //Zip
[6] => '2000-01-01' //Date of Birth
[7] => 'Male' //Gender
[8] => '12' //Grade
1 => //Student 2
array
[0] => 'Jane'
[1] => 'Smith'
[2] => '99 Main St'
[3] => 'Boston'
[4] => 'MA'
[5] => '01234'
[6] => '2000-02-02'
[7] => 'Female'
[8] => '10'
UPDATE: For those that are interested, here is my final function after I fixed the errors:
<? function addToDatabase ($dataArray) {
//Connnect to Database
$host = 'myHost';
$un = 'myUsername';
$pw = 'myPassword';
$db_name = 'myTable';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbName", $un, $pw);
echo 'Connected to database<br>';
$sql = "INSERT INTO studentData (originallyAddedOn, inputMethod, studentFirst, studentLast, studentStreet, studentCity, studentState, studentZip, studentDOB, studentGender, studentGrade, schoolName, schoolStreet, schoolCity, schoolState, schoolZip, schoolContactName, schoolContactTitle, schoolContactEmail, schoolContactPhone) VALUES (:originallyAddedOn, :inputMethod, :studentFirst, :studentLast, :studentStreet, :studentCity, :studentState, :studentZip, :studentDOB, :studentGender, :studentGrade, :schoolName, :schoolStreet, :schoolCity, :schoolState, :schoolZip, :schoolContactName, :schoolContactTitle, :schoolContactEmail, :schoolContactPhone)";
$q = $conn->prepare($sql);
foreach ($dataArray as $student){
$a = array (':originallyAddedOn'=>$student['timestamp'],
':inputMethod'=>$student['inputMethod'],
':studentFirst'=>$student['studentFirst'],
':studentLast'=>$student['studentLast'],
':studentStreet'=>$student['studentStreet'],
':studentCity'=>$student['studentCity'],
':studentState'=>$student['studentState'],
':studentZip'=>$student['studentZip'],
':studentDOB'=>$student['studentDOB'],
':studentGender'=>$student['studentGender'],
':studentGrade'=>$student['studentGrade'],
':schoolName'=>$student['schoolName'],
':schoolStreet'=>$student['schoolStreet'],
':schoolCity'=>$student['schoolCity'],
':schoolState'=>$student['schoolState'],
':schoolZip'=>$student['schoolZip'],
':schoolContactName'=>$student['schoolContactName'],
':schoolContactTitle'=>$student['schoolContactTitle'],
':schoolContactEmail'=>$student['schoolContactEmail'],
':schoolContactPhone'=>$student['schoolContactPhone']);
if ($q->execute($a)) {
// Query succeeded.
} else {
// Query failed.
echo $q->errorCode();
}
// close the database connection
$dbh = null;
echo "Insert Complete!";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
You dont need to bind your variables. Ive done this before with similar code. Its hard to say whats going wrong though. Do you get an exception - if so what is it?
The only thing i see wrong is you have your preparation inside the loop... should be more like:
try {
$conn = new PDO("mysql:host=$host;dbname=$dbName", $un, $pw);
echo 'Connected to database<br>';
$sql = "INSERT INTO studentData (originallyAddedOn, inputMethod, studentFirst, studentLast, studentStreet, studentCity, studentState, studentZip, studentDOB, studentGender, studentGrade, schoolName, schoolStreet, schoolCity, schoolState, schoolZip, schoolContactName, schoolContactTitle, schoolContactEmail, schoolContactPhone) VALUES (:originallyAddedOn, :inputMethod, :studentFirst, :studentLast, :studentStreet, :studentCity, :studentState, :studentZip, :studentDOB, :studentGender, :studentGrade, :schoolName, :schoolStreet, :schoolCity, :schoolState, :schoolZip, :schoolContactName, :schoolContactTitle, :schoolContactEmail, :schoolContactPhone)";
// prepare once... exceute many :-)
$q = $conn->prepare($sql);
foreach($studentDataArray as $student) {
$q->execute($yourDataArray);
// do other stuff if needed
}
} catch(PDOException $e) {
echo $e->getMessage();
}
For loops, do this (PDO or other database client libraries that support prepared statements):
prepare the SQL INSERT query.
bind the variables.
loop your array against the bind variables, execute once per iteration.
Profit.
For a PDO based example on an array with data to insert into some table that requires a single column named option.
First some data to be inserted into the database:
$options = [
['option' => "Insert Option A " . uniqid()],
['option' => "Insert Option B " . uniqid()],
['option' => "Insert Option C " . uniqid()],
];
Somewhere else, let's assume to have that $options array and care about the database interaction. This needs a connection:
$conn = new PDO('mysql:dbname=test;host=localhost', 'testuser', 'test');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
Now let's prepare the insert query. Using named parameters here like in the question, sure this works with numbered parameters, too:
$stmt = $conn->prepare('INSERT INTO config (`OPTION`) VALUES (:OPTION);');
Now let's bind the named parameter to a variable here. Take note, that the variable is prefixed (here with insert). This is actually the aliasing to the option key in the input array:
$stmt->bindParam(':OPTION', $insert_option);
So now from the numbered list above, the points 1.) prepare the SQL INSERT query. and 2.) bind the variables. has been done.
Only left is the loop over the $options array to insert the values:
foreach ($options as $insert) {
extract($insert, EXTR_PREFIX_ALL, 'insert');
$stmt->execute();
}
Making use of extract allows to set multiple variables at once based on the input array in an aliased fashion without much ado.
The full example:
$options = [
['option' => "Insert Option A " . uniqid()],
['option' => "Insert Option B " . uniqid()],
['option' => "Insert Option C " . uniqid()],
];
$conn = new PDO('mysql:dbname=test;host=localhost', 'testuser', 'test');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
# 1. Prepare
$stmt = $conn->prepare('INSERT INTO config (`OPTION`) VALUES (:OPTION);');
# 2. Bind
$stmt->bindParam(':OPTION', $insert_option);
# 3. Loop & Execute
foreach ($options as $insert) {
extract($insert, EXTR_PREFIX_ALL, 'insert');
$stmt->execute();
}

Categories