Question

I am currently trying to run a query where the current value of a mysql table column increase itself by 1... Let me show this with mysql query example

$sql = mysql_query("UPDATE `table` SET quantity=quantity+1 WHERE id='$id'");

I am unable to do this in PDO prepared statement...

$sql = "UPDATE `table` SET quantity=:quants+1 WHERE id=:userid";
$sql_prep = $db->prepare($sql);
$sql_prep->bindParam(":quants", what will i write here??);
$sql_prep->bindParam(":userid", $id);
$sql_prep->execute();

Help needed..! Thanks

Was it helpful?

Solution

You don't need to pass that as a parameter, just do:

$sql = "UPDATE `table` SET quantity=quantity+1 WHERE id=:userid";
$sql_prep = $db->prepare($sql);
$sql_prep->bindParam(":userid", $id);
$sql_prep->execute();

OTHER TIPS

You don't need the to protect quantity as you're just augmenting a value already in the db.

 $sql = "UPDATE `table` SET quantity=quantity+1 WHERE id=:userid";

You can also drop the bind line for the :quants

 $sql_prep = $db->prepare($sql);

 // NOT NEEEDED --> $sql_prep->bindParam(":quants", what will i write here??);

 $sql_prep->bindParam(":userid", $id);
 $sql_prep->execute();

Prepared statements are for protecting data being inserted from the outside into your db via your query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top