-1

I get the variable 'stock' from my database. I would like increment my variable with an update with this code:

$stock = $_POST['stock']

$nom = 'salade';
$req=("UPDATE ingredients SET stock=$stock+1 WHERE nom = :nom;");
 $stmt = $db->prepare($req);

    // execute the query
    $stmt->execute(array('nom'=>$nom));

But the problem is that my variable increment by 8 and not by 1 because I have 8 element (salade,tomatoes, bread etc). I want to increment by 1 with UPDATE.

Thanks to reading me !

4
  • SET stock=stock + $stock
    – u_mulder
    Commented Apr 14, 2020 at 11:08
  • Why not increment before update like $stock = $_POST['stock'] + 1; Commented Apr 14, 2020 at 11:14
  • 1
    using a prepared statement but still including unsanitised user input directly ... thus making this open to sql injection. Commented Apr 14, 2020 at 11:18
  • You should not set the value from the post value. Let the database increase itself. See answer from @Gilkan Commented Apr 14, 2020 at 12:33

2 Answers 2

1

Considering that you're saying all you need to is increment by 1 each row WHERE nom = :nom (I guess your actual code isn't wrong with $ instead of : or it wouldn't even "increment by 8" as you said you're already achieving... remember do edit this on your question, please):

UPDATE
    ingredients
SET
    stock=stock+1
WHERE
    nom = :nom;

Jusk pick what you already had and add 1 stock=stock+1.

0

You can use like this for variable in text query.

$req= ("UPDATE ingredients SET stock='".($stock+1)."' WHERE nom = :nom;");

Not the answer you're looking for? Browse other questions tagged or ask your own question.