【问题标题】:How to insert multiple values in a single query如何在单个查询中插入多个值
【发布时间】:2015-07-28 06:34:00
【问题描述】:

请有人帮助我。在下面的代码中,查询将执行 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++;
        }

【问题讨论】:

标签: php arrays mysqli


【解决方案1】:

在数组中获得相同数量的值之前,它不会抛出任何错误

$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')

【讨论】:

  • @Uchiha 很漂亮,但是你在循环中执行count($products),应该在循环之前保存它;p
【解决方案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) 

【讨论】:

  • 别忘了保护您的数据^^
  • 非常感谢,我知道该怎么做,,,再次感谢
  • @Bob0t 是的,亲爱的,我会保护它,但我对这样的想法感到困惑,现在它解决了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
  • 2015-02-24
  • 2010-11-13
相关资源
最近更新 更多