Reputation: 5
I have created a PHP function to insert data into a MySQL table. One of the values passed into the function is an array. The array contains unique values only. When I run the script it saves one record to the table with the field corresponding to the array storing all the array values.
This is my function which is in a separate class file:
public function importTest($val1,$valArray,$val3){
try {
$stm = $this->dbSt->prepare('INSERT INTO table (val1,valArray,val3) VALUES (:val1,:valArray,:val3)');
$stm->bindParam(':val1',$val1);
$stm->bindParam(':valArray',$valArray);
$stm->bindParam(':val3',$val3);
if($stm->execute()){
return true;
}
}catch (PDOException $e) {
echo $e->getMessage();
}
return false;
}
Setting $test
and echoing to the screen for testing purposes. This displays all unique values in the array which is what I am looking for.:
$test = implode("<br />", (array_keys($array_unique_guests)));
echo 'TEST:<br /> '.$test.' <br />'; // Displays all unique values
echo '<br /><br />';
This is where I am calling the function:
$importTest = $statsDao->importTest($getSites[$x]['site_id'],$test,$updateDate);
I am using a for loop to get values for $getSites
which calls another function.
I need all the values being echoed to the screen above as $test to be saved as new records in the table. Instead they are all being added in one record.
I would like to insert as many rows as there are values in the array. This number will change, but for example, if there are 10 values in the array, there should be 10 records added to the table, along with a date and another field. Basically, I am trying to retrieve all the values in the array and create a new record for each one when the script runs.
I hope this is clear. I've been stuck on this for a while and hoping someone can help!
Thanks!
Upvotes: 0
Views: 657
Reputation: 781964
Pass the array to the function, not an imploded string, and then use a loop in the function.
public function importTest($val1,$valArray,$val3){
try {
$stm = $this->dbSt->prepare('INSERT INTO table (val1,valArray,val3) VALUES (:val1,:val2,:val3)');
$stm->bindParam(':val1',$val1);
$stm->bindParam(':val2',$val2);
$stm->bindParam(':val3',$val3);
foreach ($valArray as $val2) {
$stm->execute();
}
}catch (PDOException $e) {
echo $e->getMessage();
return false;
}
return true;
}
You pass the array directly with:
$statsDao->importTest($getSites[$x]['site_id'], array_keys($array_unique_guests), $updateDate);
Upvotes: 1
Reputation: 393
So far I could guess from the title,
$inser = "INSERT INTO table_name(id,name,pass) VALUES";
$valuearray = array( // the array composed of values that you have prepared
[
"id" => 1,
"name" => "John Due",
"pass" => "123456"
],
[
"id" => 2,
"name" => "Jonathan",
"pass" => "123456"
],
[
"id" => 3,
"name" => "Jonny",
"pass" => "123456"
]
);
foreach($valuearray as $val)
{
$inser .= "('".$val['id']."','".$val['name']."','".$val['pass']."')";
}
echo $inser;
Upvotes: 0