Home  >  Article  >  Database  >  How to Count Rows in MySQL Using PDO?

How to Count Rows in MySQL Using PDO?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 18:26:54698browse

How to Count Rows in MySQL Using PDO?

Counting Rows Using PDO

In legacy PHP code, the mysql_num_rows() function was frequently used to count the number of rows returned by a MySQL query. However, with the adoption of PDO (PHP Data Objects), this function is no longer available.

For PDO, there are alternative methods to achieve the same functionality. One option is to use the ->fetchColumn() method:

$res = $DB->query('SELECT COUNT(*) FROM table');
$num_rows = $res->fetchColumn();

Here, $res is the result of a PDO query, and $num_rows will hold the count returned by the query.

Another option is to use a prepared statement:

$res = $DB->prepare('SELECT COUNT(*) FROM table');
$res->execute();
$num_rows = $res->fetchColumn();

Both of these methods effectively emulate the behavior of mysql_num_rows().

You can also use ->fetchColumn() to perform conditional checks, such as determining if data exists:

$res = $DB->query('SELECT COUNT(*) FROM table');
$data_exists = ($res->fetchColumn() > 0) ? true : false;

By employing these techniques, you can seamlessly count rows using PDO, mimicking the functionality of mysql_num_rows().

The above is the detailed content of How to Count Rows in MySQL Using PDO?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn