Home > other >  PDO Add/Sum value with existing one in SQL
PDO Add/Sum value with existing one in SQL

Time:12-09

I have a field with 5 and wanna add 2 to become a total of 7 but have error:

Fatal error: Uncaught Error: Call to undefined method PDO::execute() in...

My code is:

$statement = $connection->execute("
UPDATE ws_quantities 
SET quantity = quantity   :qty 
WHERE product_id = :product_id AND store_id = :store_id
");
$result = $statement->execute([
    'qty'           =>  $_POST["qty"], 
    'product_id'    =>  $_POST["product_id"], 
    'store_id'      =>  $_POST["store_id"] 
]);

Am I missing something!?

CodePudding user response:

It looks like you are calling the execute method on the $connection object instead of the $statement object. The PDO::execute method is used to execute a prepared statement, not to execute an SQL query.

Try this instead:

$query = "UPDATE ws_quantities  SET quantity = quantity   :qty WHERE product_id = :product_id AND store_id = :store_id";

$statement = $connection->prepare($query);
$result = $statement->execute([
    'qty'           =>  $_POST["qty"], 
    'product_id'    =>  $_POST["product_id"], 
    'store_id'      =>  $_POST["store_id"] 
]);

In this code, the $query variable contains the SQL query as a string. The $connection->prepare method is used to create a prepared statement from the query, and the $statement->execute method is used to execute the prepared statement with the given parameter values.

Note that this is just an example, and it's always a good idea to properly validate and sanitize user input before using it in an SQL query.

  • Related