YouTip LogoYouTip

Pdostatement Rowcount

# PDOStatement::rowCount [![Image 3: PHP PDO Reference Manual](#)PHP PDO Reference Manual](#) PDOStatement::rowCount β€” Returns the number of rows affected by the last SQL statement (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0) * * * ## Description ### Syntax 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 associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behavior is not guaranteed for all databases and should not be relied on for portable applications. * * * ## Return Value Returns the row count. * * * ## Examples ### Returning the number of deleted rows PDOStatement::rowCount() returns the number of rows affected by DELETE, INSERT, or UPDATE statements. prepare('DELETE FROM fruit'); $del->execute();/* Return the number of rows deleted */print("Return number of rows that were deleted:n"); $count = $del->rowCount();print("Deleted $count rows.n");?> The above example outputs: Return number of rows that were deleted:Deleted 9 rows. ### Counting rows returned by a SELECT statement For most databases, PDOStatement::rowCount() cannot return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same WHERE clause as the intended SELECT statement, then use PDOStatement::fetchColumn() to fetch the resulting row. This way, the application can proceed correctly. 100";if ($res = $conn->query($sql)) { /* Check the number of rows matching the SELECT statement */ if ($res->fetchColumn() > 0) { /* Issue a real SELECT statement and work with the result set */ $sql = "SELECT name FROM fruit WHERE calories > 100"; foreach ($conn->query($sql) as $row) { print "Name: " . $row['NAME'] . "n"; } } /* No rows matched -- do something else */ else { print "No rows matched the query."; }} $res = null; $conn = null;?> The above example outputs: apple banana orange pear * * PHP PDO Reference Manual](#)
← Pdostatement SetattributePdostatement Nextrowset β†’