PHP / PDO: use a simple prepared statement with returned / affected query strings?

I am new to PDO objects and cannot find any documentation that will help me. Let's say I have a simple code to delete a line:

$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'"); 

This will return the affected rows, but how can I use prepared statements with this? Can use use $dbh->prepare AND $dbh->exec or query !?

+4
source share
2 answers

It should be the same as any other statement:

 $stmt = $dbh->prepare("DELETE FROM fruit WHERE colour = ?"); $stmt->execute(array('red')); $count = $stmt->rowCount(); 

PDO Statement rowCount () should be what you want to do.

EDIT

Fixed by adding ->rowCount() , which will return a row counter. ->execute in the statement will return bool , true or false , whether the request was deleted or not. Of course, all this information is easily accessible in the PDO Statement.

+11
source

$dbh->prepare returns a PDOStatement object. Then you call $stmt->execute to get the result.

Further information in the PDO manual

Here is an example from the manual:

 <?php /* Execute a prepared statement by passing an array of insert values */ $calories = 150; $colour = 'red'; $stmt = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?'); $stmt->execute(array($calories, $colour)); ?> 
+1
source

All Articles