Home  >  Article  >  Database  >  How To Count Rows Using PDO Alternatives for mysql_num_rows?

How To Count Rows Using PDO Alternatives for mysql_num_rows?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 18:33:46150browse

How To Count Rows Using PDO Alternatives for mysql_num_rows?

Alternative for mysql_num_rows Using PDO

The legacy MySQL function mysql_num_rows is no longer available when using PHP Data Objects (PDO). To count rows in a PDO result set, there are several alternative approaches.

One method is to use the query() function to execute a query that retrieves the count of rows in the table. For instance:

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

Alternatively, you can use the prepare() and execute() methods to achieve the same result:

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

These approaches allow you to retrieve the count of rows in the result set and perform calculations or actions based on the count.

Additionally, you can directly check if data exists or is selected by comparing the result of the rowCount() method to 0:

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

You can also use this approach to set the value of your message variable based on the count of rows:

<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 Count Rows Using PDO Alternatives for mysql_num_rows?. 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