使用 For 和 While 循环更新查询

时间:2021-02-02 04:05:12

标签: php mysql mysqli sql-update product-quantity

我想使用 for 循环和 while 循环运行更新查询。因为我想更新产品数量 下单成功后根据产品id和总数量减去订单数量后在产品表中,但是查询没有成功。

我的代码:

           // Update Query 
            $update_quantity = "";
            for ($i = 0; $i < (count($_SESSION['shopping_cart'])); $i++) {

                $select_quan = "SELECT * FROM product WHERE pid = {$pid[$i]}";
                $result_quan = mysqli_query($con, $select_quan);

                // $update_quantity .= " UPDATE product SET ";

                while ($row_quan = mysqli_fetch_assoc($result_quan)) {

                    $quantity_after_order[$i] =   $row_quan['pquantity'] - ($pquantity[$i]);

                    $update_quantity .= "UPDATE product SET pquantity = '$quantity_after_order[$i]' WHERE pid=$pid[$i]; ";
                }
            }

当我运行查询时:

            // echo $update_quantity;
            if ($con->query($update_quantity) == TRUE) {
                 echo "Data Successfully Updated";
             }
             else{
                  echo "Error: $update_quantity <br> $con->error";
             }

它给出的输出:

Error: UPDATE product SET pquantity = '246' WHERE pid=7; UPDATE product SET pquantity = '11' WHERE pid=32;

您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,了解要在第 1 行的“UPDATE product SET pquantity = '11' WHERE pid=32' 附近使用的正确语法

如果有另一种方式运行此查询,在订单成功后根据 product_id 更新数据库中的数量,请告诉我。

1 个答案:

答案 0 :(得分:0)

在一个语句中,您可以:

UPDATE product SET pquantity =
    CASE pid
        WHEN 7 THEN '246'
        WHEN 32 THEN '11'
    END
WHERE pid in (7,32);

有时在确实有大量行的情况下,您会使用临时表:

CREATE TEMPORARY TABLE product_update (pid int, pquantity varchar(10));
INSERT INTO product_update VALUES (7,'246'),(32,'11'),....;
UPDATE product_update JOIN product USING (pid) SET product.pquantity=product_update.pquantity;
DROP TEMPORARY TABLE product_update;