There are many conflicting statements around. What is the best way to row count using PDO in PHP? Before using PDO, I just simply used mysql_num_rows
.
fetchAll
is something I won't want because I may sometimes be dealing with large datasets, so not good for my use.
Do you have any suggestions?
As I wrote previously in an answer to a similar question, the only reason
mysql_num_rows()
worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you.So in PDO, your options are:
FOUND_ROWS()
function.fetchAll()
function to fetch all the rows into an array, then usecount()
on it.SELECT COUNT(*)
, as karim79 suggested.If you just want to get a count of rows (not the data) ie. using COUNT(*) in a prepared statement then all you need to do is retrieve the result and read the value:
Actually retrieving all the rows (data) to perform a simple count is a waste of resources. If the result set is large your server may choke on it.
Have a look at this link: http://php.net/manual/en/pdostatement.rowcount.php It is not recommended to use rowCount() in SELECT statements!
Use parameter
array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)
, else show -1:Usen parametro
array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)
, sin ello sale -1example:
Answering this because I trapped myself with it by now knowing this and maybe it will be useful.
Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by
count($array)
, and output results withforeach
. For example:A quick one liner to get the first entry returned. This is nice for very basic queries.
Reference