0

I would like to run an update query with an if statement on a MySQL database using PHP. I would like to update the stock in my eshop, but only if the quantity that customer order exists. I tried something like this

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

or like this

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

Is there anyone that could help me with the issue I'm having?

1
  • What error are you getting? Commented May 26, 2014 at 12:59

1 Answer 1

2

You can't return expression like stock = stock from your CASE . Try the following :

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

or

$sql = "UPDATE products 
        SET stock = IF(stock >= $quantity, (stock - $quantity), stock)
        WHERE product = '$product' "
Sign up to request clarification or add additional context in comments.

1 Comment

+1 . . . But the single quotes around "quantity" are superfluous (because it should be a number).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.