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()) ?
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()) ?
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 aSELECTstatement.
Instead, usePDO::query()to issue aSELECT COUNT(*)statement with the same predicates as your intendedSELECTstatement, then usePDOStatement::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.
Although PDO apparently has all means to count the number of rows returned from a select query for mysql, what is more important is that there is no use for such a function in the first place.
Every time you have an idea to use rowCount() for a SELECT query, it would be either superfluous or even harmful. See PDO rowCount():
Another option that may be closer to the num_rows variable in mysqli and the corresponding C API function mysql_num_rows(). Is to use the MySQL function FOUND_ROWS() that returns the same information without having to count all the records in the result again.
Example:
$pdoDB->query('SELECT FOUND_ROWS()')->fetchColumn()
The Easiest
$stmt = $datalink->query('SELECT * FROM projects');
$rows = $stmt->fetchAll();
$num_rows = count($rows);
echo $num_rows ;