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.
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.
The mysqli_num_rows() function returns the number of rows in a result set.
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.
Yes, it is possible.
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.
In Pdo you use rowCount
. Example: $string-> rowCount ();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With