Home  >  Article  >  Database  >  How to Replicate mysql_num_rows Functionality Using PDO?

How to Replicate mysql_num_rows Functionality Using PDO?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 16:16:02681browse

How to Replicate mysql_num_rows Functionality Using PDO?

Using PDO to Replace mysql_num_rows

Question:

Reworking a PHP application to use PDO, developers may encounter the need to replicate the functionality of mysql_num_rows for counting the number of rows in a result set. How can this be achieved using PDO?

Answer:

PDO provides two methods to count rows:

Method 1: Direct Query

<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table');
$num_rows = $res->fetchColumn();</code>

Method 2: Prepared Statement

<code class="php">$res = $DB->prepare('SELECT COUNT(*) FROM table');
$res->execute();
$num_rows = $res->fetchColumn();</code>

Data Existence Check

In addition to row counting, these methods can be used to check for data existence:

<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table');
$data_exists = ($res->fetchColumn() > 0) ? true : false;</code>

Example Use Case

To determine if there is only one row in a table, the following code can be used:

<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table');
$message = ($res->fetchColumn() > 0) ? array('status' => 'ok') : array('status' => 'error');</code>

The above is the detailed content of How to Replicate mysql_num_rows Functionality 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