1

I would like that for "salade", when I click on the button "+" It add me +1 on my stock.

For example, I have a 25 salade available, When I click on "+" I have now 26 salades,

Here my code:

<?php
if(isset($_POST['stock'])){
    $stock = $_POST['stock'];
    $stock = $stock +1;
}
?>  
<?php $req=$db->prepare("UPDATE ingredients SET stock =:stock WHERE nom = 'salade'");
                    $req->execute(array('stock' =>$stock));
Dharman
  • 30,962
  • 25
  • 85
  • 135
jacques
  • 23
  • 5
  • I'm not certain if this is what you're asking, but are you looking for `UPDATE ingredients SET stock = stock + 1 ...` ? – iainn Apr 14 '20 at 10:20
  • Do you mean `=:stock` should be `= {$stock}`? Also see https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Zoe Edwards Apr 14 '20 at 10:21
  • 1
    @ThomasEdwards Definitely not. – Dharman Apr 14 '20 at 10:21
  • 1
    it's a placeholder and that's just right @ThomasEdwards. Using your example the code will be susceptible to SQL injection – jrswgtr Apr 14 '20 at 10:22

1 Answers1

2

When you click on the "+" button, It adds +1 on your current stock, So you can update it with the current value like stock = stock + 1,

<?php 
$nom = 'salade';
$req=$db->prepare("UPDATE ingredients SET stock = stock + 1 WHERE nom =:nom");
$req->execute(array('nom' =>$nom));
?>
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • 1
    It works but it puts me not +1 but +8 always, it 's probably because I have 8 elements ( salade,tomatoes,...... ) – jacques Apr 14 '20 at 10:26
  • @jacques if it adds 8 and you say you have 8 elements, that gives me the feeling that there is something wrong in your client side code that triggers this PHP script 8 times. Can you show us your JavaScript code that gets executed when you click on "+1" button. – Accountant م Apr 14 '20 at 12:43
  • yes , it's good it works now, thx !! But I would like know, Why when I do F5 it refresh me the page, but It add me too +1 ??? – jacques Apr 14 '20 at 13:14