Have a php array of objects, each object has some values from the same set of keys. Have a mysql database where the fields match the set of keys in each object. Want to write values from each object in the array to mysql using pdo, and a loop. Any suggestions would be great!
PHP: (initiate some variables), 3 arrays with data turned into objects put into a "$_STORAGE" array that represents session variable:
<?php
$Q = $A1 = $A2 = $A3 = $A4 = $A5 = $A6 = "";
$array1 = array(
"Q" => "q1",
"A1" => "a",
"A3" => "c",
"A6" => "f"
);
$array2 = array(
"Q" => "q2",
"A4" => "j",
"A5" => "k",
);
$array3 = array(
"Q" => "q3",
"A1" => "m",
"A2" => "n",
"A3" => "o",
"A4" => "p",
"A5" => "q",
"A6" => "r"
);
$_POST1 = (object) $array1;
$_POST2 = (object) $array2;
$_POST3 = (object) $array3;
$_STORAGE = [];
$_STORAGE['answers'][0] = $_POST1;
$_STORAGE['answers'][1] = $_POST2;
$_STORAGE['answers'][2] = $_POST3;
?>
Here's the MySql table (data_table) written to the database (data_base). The fields are the same as the object keys:
CREATE TABLE data_base.data_table
(ID INT NOT NULL AUTO_INCREMENT, Q VARCHAR(20), A1 VARCHAR(20), A2
VARCHAR(20), A3 VARCHAR(20), A4 VARCHAR(20), A5 VARCHAR(20),
A6 VARCHAR(20), Date TIMESTAMP , PRIMARY KEY (ID));
Here's the pdo code (without exception handling) that writes one object to the database:
<?php
//connect to database
include "connection_info_data_base.php";
// sql query insert into data_table
$sql = "INSERT INTO `data_table` (`Q`,`A1`,`A2`,`A3`,`A4`,`A5`,`A6`,) VALUES(:Q,
:A1, :A2, :A3, :A4, :A5, :A6)";
$stmt = $db->prepare($sql);
$stmt->bindParam(':Q', $Q);
$stmt->bindParam(':A1', $A1);
$stmt->bindParam(':A2', $A2);
$stmt->bindParam(':A3', $A3);
$stmt->bindParam(':A4', $A4);
$stmt->bindParam(':A5', $A5);
$stmt->bindParam(':A6', $A6);
//insert $sql query to server
$stmt->execute();
?>
How to write a loop that will assign values from $_STORAGE["answers"][0] to the variables $Q, $A1, $A2, $A3, $A4, $A5, $A6, with "" as value if there is not value for that key in the object, then run the pdo code, insert the values into row 1 in database, start loop again, rewrite the variable values from $_STORAGE["answers"][1], overwriting all values and run pdo code again to write row 2 in database, and then again for row 3?