如何通过传递动态变量使用PHP和mysqli_query()命令更新MySQL中的多行?

时间:2014-02-04 02:26:39

标签: php mysqli

我正在尝试更新这些行,以便在有人购买后删除购物车中的商品。 问题是我只将第一组改为我想要的数量。 我怎样才能做到这一点? 如果我回显$ update变量,它会显示每个项目的UPDATE查询。 我只是无法让sql3 var重复。

$id_str_array = ['44-1','43-2']    

foreach ($id_str_array as $key => $value) {

  $id_quantity_pair = explode("-", $value); // Uses Hyphen(-) as delimiter to separate   product ID from its quantity
  $product_id = $id_quantity_pair[0]; // Get the product ID
  $product_quantity = $id_quantity_pair[1]; // Get the quantity
  $sql2 = mysqli_query($con, "SELECT * FROM INVENTORY WHERE ID = $product_id");
  while($row2 = mysqli_fetch_array($sql2)){
    $p_stock = ($row2['PRODUCT_STOCK'] - $product_quantity);
    $update .= "UPDATE INVENTORY SET PRODUCT_STOCK= $p_stock WHERE ID= $product_id;";
  }
  $sql3 = mysqli_query($con, $update);
}

mysqli_query函数不应该为foreach循环中的每个值运行一次 任何帮助将不胜感激

3 个答案:

答案 0 :(得分:3)

这是使用准备好的声明的绝佳机会。它们经过优化,可以使用不同的值运行多次。例如......

$stmt = $con->prepare('UPDATE INVENTORY SET PRODUCT_STOCK = (PRODUCT_STOCK - ?) WHERE ID = ?');
if (!$stmt) {
    throw new Exception($con->error, $con->errno);
}
$stmt->bind_param('ii', $product_quantity, $product_id);

foreach ($id_str_array as $value) {
    list($product_id, $product_quantity) = explode('-', $value);

    if (!$stmt->execute()) {
        throw new Exception($stmt->error, $stmt->errno);
    }
}

答案 1 :(得分:0)

试试这个:

$id_str_array = ['44-1','43-2']    
$update = "";
foreach ($id_str_array as $key => $value) {
  $id_quantity_pair = explode("-", $value);
  $product_id = $id_quantity_pair[0]; // Get the product ID
  $product_quantity = $id_quantity_pair[1]; // Get the quantity
  $update .= "UPDATE INVENTORY SET PRODUCT_STOCK=PRODUCT_STOCK - "
           . $product_quantity . " WHERE ID= $product_id; ";
}
$sql3 = mysqli_multi_query($con, $update);

答案 2 :(得分:-2)

试试这个:

$id_str_array = ['44-1','43-2']    

 foreach ($id_str_array as $key => $value) {

  $id_quantity_pair = explode("-", $value); // Uses Hyphen(-) as delimiter to separate   product ID from its quantity
  $product_id = $id_quantity_pair[0]; // Get the product ID
  $product_quantity = $id_quantity_pair[1]; // Get the quantity

  $sql2 = mysqli_query($con, "SELECT * FROM INVENTORY WHERE ID = $product_id");
  $x = 1;
  while($row2 = mysqli_fetch_array($sql2))
  {
   $p_stock[$x] = ($row2['PRODUCT_STOCK'] - $product_quantity);
   $x++;
  }
  for($x=1;$x <count($p_stock[$x]); $x++)
  {
     $update = "UPDATE INVENTORY SET PRODUCT_STOCK= '$p_stock' WHERE ID= '$product_id[$x]' ";
     $sql3 = mysqli_query($con, $update);
  }
 }

希望这会有所帮助..