使用IF更新PHP查询

时间:2014-05-26 12:38:32

标签: php mysql sql

我想使用PHP在MySQL数据库上使用if语句运行更新查询。 我想在我的eshop中更新库存,但仅限于客户订单的数量存在。 我试过这样的事情

$updatequery = "UPDATE products 
                SET stock 
                CASE WHEN (stock >= '$quantity') THEN (stock=stock-'$quantity')
                    ELSE (stock= stock)
                END
                WHERE product='$product'"; `

或者像这样

$sql = "UPDATE products SET\n"
. "stock = IF(stock>=$quantity, stock=stock-$quantity, IF(stock<=$quantity, stock=stock) )\n"
. "WHERE product=$product"; `

有没有人可以帮我解决我遇到的问题?

1 个答案:

答案 0 :(得分:2)

您无法从stock = stock返回CASE这样的表达式。请尝试以下方法:

$sql = "UPDATE products 
        SET stock = CASE
                        WHEN stock >= $quantity THEN (stock - $quantity)
                        ELSE stock 
                    END
        WHERE product = '$product' "

<强>

$sql = "UPDATE products 
        SET stock = IF(stock >= $quantity, (stock - $quantity), stock)
        WHERE product = '$product' "