PDOStatement::rowCount — Returns the number of rows affected by the previous SQL statement (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
int PDOStatement::rowCount ( void )
PDOStatement::rowCount() Returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the related PDOStatement was a SELECT statement, some data may return the number of rows returned by this statement. However, this approach is not guaranteed to work for all data, and should not be relied upon for portable applications.
Returns the number of rows.
PDOStatement::rowCount() Returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.
<?php/* Delete all rows from the FRUIT data table*/$del = $dbh->prepare('DELETE FROM fruit');$del->execute();/* Return the number of deleted rows*/print ("Return number of rows that were deleted:n");$count = $del->rowCount();print("Deleted $count rows.n");?>
The above example output:
Return number of rows that were deleted:Deleted 9 rows.
For most databases, PDOStatement::rowCount() cannot return the number of rows affected by a SELECT statement. Alternatively, use PDO::query() to issue a SELECT COUNT(*) statement with the same conditional expression as the originally intended SELECT statement, and then use PDOStatement::fetchColumn() to fetch the next row. This way the application can execute correctly.
<?php$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";if ($res = $conn->query($sql)) { /* Check the number of rows that match the SELECT statement*/ if ($ res->fetchColumn() > 0) { /* Issue a real SELECT statement and operate on the returned results*/ $sql = "SELECT name FROM fruit WHERE calories > 100"; foreach ($conn->query($sql) as $row) { print "Name: " . $row['NAME'] . "n"; } } /* No matching rows - - Execute other */ else { print "No rows matched the query."; }}$res = null;$conn = null;?>
The output result of the above example is:
applebananaorangepear