[英]Insert values into database from arrays
My php looks like this: 我的PHP看起来像这样:
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[]. 我的数据库中有三个字段名称,分别为Ingredientamount,fasitionType和Ingredientname,分别对应于分配给$ 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? 我的问题是:如何使用代码获取$ rows [](这是一个多维数组)并将每一行插入到像我的数据库中?
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 毕竟,您会在
$sql
得到类似的信息
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?
感谢您的回答,但是Ingredientamount,fastentType和Ingredientname的值是动态的,所以我认为这行不通吗?
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 ";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.