I'm trying to get started with PDO and am having some trouble. Here's my original code:
$query = "
UPDATE `products`
SET `product_qty` = '{$_GET['product_qty']}'
WHERE `product_id` = '{$_GET['product_id']}'
";
mysql_query($query) or die(mysql_error());
That works fine, but when I try to translate that to PDO syntax:
$db->prepare('
UPDATE products
SET product_qty = :product_qty
WHERE product_id = :product_id
');
try
{
$db->execute(array(':product_qty' => $_GET['product_qty'], ':product_id' => $_GET['product_id']));
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
I get the error:
Fatal error: Call to undefined method PDO::execute() in ...
Could someone help me get my first PDO query working?
$pdo = new PDO($dsn, $user, $passwd); A new PDO object is created. We pass the constructor the data source name and the user name and password. The PDO class represents a connection between PHP and a database server.
Description ¶ Prepares an SQL statement to be executed by the PDOStatement::execute() method. The statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.
PDO—PHP Data Objects—are a database access layer providing a uniform method of access to multiple databases. It doesn't account for database-specific syntax, but can allow for the process of switching databases and platforms to be fairly painless, simply by switching the connection string in many instances.
The $db->prepare()
returns a PDOStatement
which has the execute()
method.
$stmt = $db->prepare('UPDATE products
SET product_qty = :product_qty
WHERE product_id = :product_id');
$stmt->execute(array(
':product_qty' => $_GET['product_qty'],
':product_id' => $_GET['product_id']
));
$db->prepare()
returns a PDOStatement
object. You need to call execute()
on that, not on $db
.
I refer ya to the example... the prepare creates a statement, and it's that that you run execute() on...
<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>
The call to prepare
returns a PDOStatement
, it is this that you need to execute
. Try the following:
$sth = $db->prepare('
UPDATE products
SET product_qty = :product_qty
WHERE product_id = :product_id
');
$sth->execute(array(':product_qty' => $_GET['product_qty'], ':product_id' => $_GET['product_id']));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With