Current Location: Home> Latest Articles> Avoid misuse of PDOStatement::rowCount to get the number of SELECT query results

Avoid misuse of PDOStatement::rowCount to get the number of SELECT query results

gitbox 2025-05-20

In PHP, when using PDO (PHP Data Objects) to connect to a database, PDOStatement::rowCount is a commonly used function that is usually used to return the number of rows affected in the previous SQL query. However, for SELECT queries, many developers mistakenly use rowCount as a tool to get the number of query results. In this article, we will discuss in detail why PDOStatement::rowCount should not be misused to get the number of results of SELECT queries.

1. How the rowCount function works

First, we need to understand how rowCount works. The PDOStatement::rowCount function returns the number of rows affected since the last SQL statement executed. In INSERT , UPDATE , or DELETE statements, rowCount returns the number of rows affected by these statements.

However, rowCount 's performance in SELECT queries is more complicated, depending on the database driver used and the specific query execution method. For example:

  • In some database drivers (such as MySQL), rowCount may not return any meaningful value for SELECT queries, especially if the query results are not doing any actual data extraction