Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO - Num Rows

Tags:

php

mysql

pdo

PDO apparently has no means to count the number of rows returned from a select query (mysqli has the num_rows variable).

Is there a way to do this, short of using count($results->fetchAll()) ?

like image 505
Ian Avatar asked Apr 23 '10 17:04

Ian


People also ask

How do I check the number of rows in PDO?

PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement. print("Return number of rows that were deleted:\n"); $count = $del->rowCount();

How can I count rows in PHP?

We can get the total number of rows in a table by using the MySQL mysqli_num_rows() function. Syntax: mysqli_num_rows( result ); The result is to specify the result set identifier returned by mysqli_query() function.

How do I find the number of rows in a table?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.


1 Answers

According to the manual, there is a PDOStatement->rowCount method ; but it shouldn't be used (quoting) :

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement.
Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned.
Your application can then perform the correct action.


If you already have a recordset, and want to know how many lines are in it, you'll have to fetch the data, using one of the fetch* methods ; and use count -- like you suggested.

like image 67
Pascal MARTIN Avatar answered Oct 21 '22 06:10

Pascal MARTIN