Row count with PDO

前端 未结 23 3730
春和景丽
春和景丽 2020-11-21 22:57

There are many conflicting statements around. What is the best way to get the row count using PDO in PHP? Before using PDO, I just simply used mysql_num_rows.

23条回答
  •  执笔经年
    2020-11-21 23:26

    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:

    1. Use PDO's fetchAll() function to fetch all the rows into an array, then use count() on it.
    2. Do an extra query to SELECT COUNT(*), as karim79 suggested.
    3. Use MySQL's FOUND_ROWS() function UNLESS the query had SQL_CALC_FOUND_ROWS or a LIMIT clause (in which case the number of rows that were returned by the query and the number returned by FOUND_ROWS() may differ). However, this function is deprecated and will be removed in the future.

提交回复
热议问题