请有人帮助我。在下面的代码中,查询将执行3次,意味着查询执行将取决于数组中的元素数量。 请指导我如何通过一次插入所有数据来运行此查询
$products = array("shirt" , "paint" , "socks");
$price = array("200" , "600" , "50");
$quantity = array("3" , "2" , "2");
$num = 0; while($num <= count($products))
{
$mysqli->query("insert into new_order set
product = '".$products[$num]."' ,
price = '".$price[$num]."' ,
quantity = '".$quantity[$num]."'
");
$num++;
}
答案 0 :(得分:2)
迭代$products
中的每个项目以构建$sql
字符串:
$sql = "insert into new_order(product, price, quantity) values ";
for($i=0;$i<count($products);$i++){
$sql .= "({$products[$i]}, {$price[$i]}, {$quantity[$i]}),";
}
$sql = substr($sql,0,-1); //cut off the trailing comma
$mysqli->query($sql);
// insert into new_order(product, price, quantity) values (shirt, 200, 3),(paint, 600, 2),(socks, 50, 2)
答案 1 :(得分:2)
它不会抛出任何错误,直到您在数组中获得相同数量的值
$counts = count($products);
$query = "insert into new_order (product,price,quantity) values ";
foreach($products as $key => $value){
$query .= "('$value','$price[$key]','$quantity[$key]')";
$query .= (++$key == $counts) ? '' : ',';
}
$mysqli->query($query);
查询看起来像:
//insert into new_order (product,price,quantity) values('shirt','200','3'),('paint','600','2'),('socks','50','2')