Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO - alternative for mysqli_num_rows

Tags:

php

pdo

mysqli

With mysqli I can get the number of rows from a select query by using mysqli_num_rows. I can't find a way to do that with PDO without having to do a separate query like SELECT COUNT(*)? I don't see the point in doing a separate query when I already have a recordset.

like image 222
westcoast Avatar asked Oct 01 '14 09:10

westcoast


People also ask

Which is better MySQLi or PDO?

Both MySQLi and PDO have their advantages: PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.

What does Mysqli_num_rows do in PHP?

The mysqli_num_rows() function returns the number of rows in a result set.

Is PDO safer than MySQLi?

Is it still secure to use MySQLi, or should I use PDO? Both Mysqli and PDO support query parameters, which is the best way in general to protect against SQL injection. I prefer PDO because it makes it a little bit easier to write the code to use query parameters, but they work equally well in either PHP extension.

Can I use both PDO and MySQLi?

Yes, it is possible.


2 Answers

You could use SQL_CALC_FOUND_ROWS as documented here. For example:

$result = $db->prepare("SELECT SQL_CALC_FOUND_ROWS id, name FROM fruit WHERE calories > 100"); 
$result->execute();
$result = $db->prepare("SELECT FOUND_ROWS()"); 
$result->execute();
$row_count =$result->fetchColumn();
echo $row_count;

This option is normally used to get full match counts when you have a LIMIT clause, however, it works just fine without one, and it's much more efficient than issuing the same query again with a COUNT(*) since it just retrieves the count value stored by the first query value and does not have to run another full query.

like image 94
Synchro Avatar answered Oct 26 '22 07:10

Synchro


In Pdo you use rowCount. Example: $string-> rowCount ();

like image 37
Kommodore Avatar answered Oct 26 '22 08:10

Kommodore