Home > Database > Mysql Tutorial > body text

How to Count Rows in MySQL Using PDO?

Mary-Kate Olsen
Release: 2024-10-24 18:26:54
Original
697 people have browsed it

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();
Copy after login

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();
Copy after login

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;
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!