PDO::exec
PDO::exec — Executes an SQL statement and returns the number of affected rows (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
Description
Syntax
int PDO::exec ( string $statement )
PDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement.
PDO::exec() does not return results from a SELECT statement. For SELECT statements that you only need to issue once, consider using PDO::query().
Parameter Description:
statement: The SQL statement to be prepared and executed.
Return Value
PDO::exec() returns the number of rows that were modified or deleted by the SQL statement. If no rows were affected, PDO::exec() returns 0.
The following example relies on the return value of PDO::exec() incorrectly, where a statement with 0 affected rows would cause a call to die():
<?php
$db->exec() or die(print_r($db->errorInfo(), true));
?>
Examples
Executing a DELETE statement
Count the number of rows deleted by a DELETE statement without a WHERE clause.
<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
/* Delete all rows from the FRUIT table where the condition is met */
$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");
/* Return the number of deleted rows */
print("Deleted $count rows.\n");
?>
The above example will output:
Deleted 1 rows.