-2

I have a sql command that inserts a value into the table, but if that id already exists, it will insert it into the quantity column I have a sql command that inserts a value into the table, but how do I do it if that id already exists it will insert it into the quantity column and add each time that id repeats

  • Do a php check before update/insert, does the id already exist? If it does exits, then **update** that id with +1 on quantity column. If not then **create/insert** new row. – Kip Jun 02 '22 at 21:38

1 Answers1

0

i assume you connected by pdo.



$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id=?");
$stmt->execute([$id]); 
$result= $stmt->fetch();

if($result){

   $sql = "UPDATE your_table SET quantity=? WHERE id=?";
   $stmt= $pdo->prepare($sql);
   $stmt->execute([($quantity+$result['quantity']),$result['id']);

}else{
  $sql = "INSERT INTO your_table (id, quantity) VALUES (?,?)";
  $stmt= $pdo->prepare($sql);
  $stmt->execute([$id, $quantity]);
}
yusuf__
  • 7
  • 4