简体   繁体   中英

Insert values into database from arrays

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:

  1. ingredientamount => 34, ingredientType => Centiliter, ingredientname => Chicken
  2. ingredientamount => 26, ingredientType => Grams, ingredientname => Cheddar Cheese

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!

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 ";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM