Reputation: 3522
My php looks like this:
for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
$rows[] = array(
'ingredientamount' => $ingredientQTY[$i],
'ingredientType' => $measurements[$i],
'ingredientname' => $ingredientNAME[$i]
);
print_r($rows[$i]);
}
which prints out an array like this:
Array (
[ingredientamount] => 34
[ingredientType] => Centiliter
[ingredientname] => CHicken )
Array (
[ingredientamount] => 26
[ingredientType] => Grams
[ingredientname] => Cheddar Cheese )
I have three fieldnames in my database called ingredientamount, ingredientType, and ingredientname, which correspond to the two arrays which are assigned to $rows[]. So, if I had the arrays working, my database would look like this:
My question is: How can I use my code to take the $rows[] (which is a multidimensional array) and insert each row into a database like mine?
Thanks for all help!
Upvotes: 0
Views: 39
Reputation: 1850
Try this code:
<?php
$rows = array();
$rows[] = array('ingredientamount' => '34', 'ingredientType' => 'Centiliter', 'ingredientname' => 'CHicken' );
$rows[] = array('ingredientamount' => '26', 'ingredientType' => 'Grams', 'ingredientname' => 'Cheddar Cheese' );
$sql = "INSERT `myTableName` (`ingredientamount`,`ingredientType`,`ingredientname`) VALUES ";
$coma = '';
foreach ($rows as $oneRow) {
$sql .= $coma."('".implode("','",$oneRow)."')";
$coma = ', ';
}
$result = $db->query($sql);
?>
You'll get something like this in $sql
after all
INSERT `myTableName` (`ingredientamount`,`ingredientType`,`ingredientname`) VALUES ('34','Centiliter','CHicken'), ('26','Grams','Cheddar Cheese')
It is just draft code with no errors checking or input control that is actually required, but it gives the idea of how it works. I believe you can add all the rest by yourself.
EDIT
thanks for the answer but the values of ingredientamount, ingredientType, and ingredientname are dynamic so I dont think this would work?
not a problem at all. just change this line
$sql = "INSERT `myTableName` (`ingredientamount`,`ingredientType`,`ingredientname`) VALUES ";
to this
$sql = "INSERT `myTableName` (`".implode('`,`',array_keys($rows[0]))."`) VALUES ";
Upvotes: 1