Row count with PDO

前端 未结 23 3152
春和景丽
春和景丽 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:18

    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:

    $sql = "SELECT count(*) FROM `table` WHERE foo = bar";
    $statement = $con->prepare($sql); 
    $statement->execute(); 
    $count = $statement->fetch(PDO::FETCH_NUM); // Return array indexed by column number
    return reset($count); // Resets array cursor and returns first value (the count)
    

    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.

提交回复
热议问题