如何在php mysql中更新多行

时间:2017-04-17 15:26:26

标签: php mysql

我有一些代码可以像这样更新php mysql中的多行。

<?php 

$idOrder = $_GET['idOrder'];

$conn = new MySQLi('localhost','root','','project_ecommerce');

$query_select = "SELECT status FROM order_product WHERE id_order='".$idOrder."'";
$sql_select = $conn->query($query_select);
$result_select = $sql_select->fetch_assoc();
$status ='';

if ($result_select['status'] == 0) {
    $status .= 1;
}else{
    $status .= 0;
}

$query_update = "UPDATE order_product SET status='".$status."' WHERE id_order='".$idOrder."'";
$sql_update = $conn->query($query_update);

if ($sql_update == TRUE) {

    $query_select_product = "SELECT order_product.id_product AS ID_PRD, order_product.status AS STATUS, order_product.qty AS QTY_ORD, products.stock AS STOCK FROM order_product JOIN products ON order_product.id_product = products.id_product WHERE order_product.id_order ='".$idOrder."'";
    $sql = $conn->query($query_select_product);
    $result = $sql->fetch_all(MYSQLI_ASSOC);
    $stock_update='';

    for ($i=0; $i < count($result); $i++) { 

        if ($result[$i]['STATUS'] == 0) {

            $stock_update .= ($result[$i]['STOCK']+$result[$i]['QTY_ORD']);

        }else{

            $stock_update .= ($result[$i]['STOCK']-$result[$i]['QTY_ORD']);

        }

        $update_product = "UPDATE products SET stock='".$stock_update."' WHERE id_product='".$result[$i]['ID_PRD']."'";
        $sql_update_product = $conn->query($update_product);

    }   

}

echo $idOrder;
?>

如果status更新为1,我会给出这样的结果:

+----------------+-------+
| id_product     | stock |
+----------------+-------+
| PRD-0416-17-1  |   100 |
| PRD-0416-17-10 |   100 |
| PRD-0416-17-11 |    98 |
| PRD-0416-17-12 |  9898 |
+----------------+-------+

如果status更新为0,我会给出这样的结果:

+----------------+---------+
| id_product     | stock   |
+----------------+---------+
| PRD-0416-17-1  |     100 |
| PRD-0416-17-10 |     100 |
| PRD-0416-17-11 |     100 |
| PRD-0416-17-12 | 1009900 |
+----------------+---------+

我如何解决它?

1 个答案:

答案 0 :(得分:2)

您在这些作业中使用.=,这会将前一行的结果与前一个值$stock_update连接起来。它们应该只是=

    if ($result[$i]['STATUS'] == 0) {
        $stock_update = ($result[$i]['STOCK']+$result[$i]['QTY_ORD']);
    }else{
        $stock_update = ($result[$i]['STOCK']-$result[$i]['QTY_ORD']);
    }

这一切都可以在一个查询中完成:

UPDATE order_product AS o
JOIN product AS p ON o.id_product = p.id_product
SET o.status = NOT o.status,
    p.stock = IF(o.status = 0, p.stock + o.qty_ord, p.stock - o.qty_ord)
WHERE o.id_order = $idOrder