The problem with using PDO for the first time

I am trying to get started with PDO and I am having problems. Here is 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()); 

This works fine, but when I try to translate this into 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 an error message:

Fatal error: call to undefined PDO :: execute () method in ...


Can someone help me get my first PDO request?

+6
source share
4 answers

$db->prepare() returns a PDOStatement that 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'] )); 
+5
source

$db->prepare() returns a PDOStatement object. You need to call execute() , not on $db .

+4
source

I refer to ya for an example ... preparation creates an operator, and this is what 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)); ?> 
+1
source

The prepare call returns a PDOStatement , 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'])); 
+1
source

Source: https://habr.com/ru/post/919689/


All Articles