Home > Database > Mysql Tutorial > body text

How to Replicate mysql_num_rows Functionality Using PDO?

Linda Hamilton
Release: 2024-10-24 16:16:02
Original
680 people have browsed it

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

Method 2: Prepared Statement

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

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

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

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!

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!