2015-12-31 18:46
浏览 34

php pdo - 检索结果和行数 - 便携式解决方案

I'm currently querying the db twice to retrieve the row count of my result set, and my result set before I run loops on the rows returned like this:

$result = $db->query("SELECT COUNT(*) FROM mytable");
$result1 = $db->query("SELECT * FROM mytable");

$count = $result->fetchColumn();

if($count == $value){

while($row = $result1->fetch(PDO::FETCH_ASSOC)){
//execute code
} elseif($count == $value2) { 
//execute other code 

I've just converted to PDO and so don't know it as well. The code used to use mysql_num_rows. I'm looking for a way I can do this without querying the db twice, this solution that I've been using works for small purposes but is obviously unnecessary load on the database if it were scaled. Many Thanks

EDIT: My reason for moving to PDO is for it's portability features, and thus rowCount() isn't suitable in every instance.

图片转代码服务由CSDN问答提供 功能建议

我目前正在查询数据库两次,以检索我的结果集的行数,以及我之前的结果集 在这样返回的行上运行循环:

  $ result = $ db-> query(“SELECT COUNT(*)FROM mytable”); 
 $ result1 = $  db-> query(“SELECT * FROM mytable”); 
 $ count = $ result-> fetchColumn(); 
if($ count == $ value){
while($ row)  = $ result1-> fetch(PDO :: FETCH_ASSOC)){
} elseif($ count == $ value2){
 <  / code>  

我刚刚转换为PDO,因此也不知道它。 用于使用 mysql_num_rows 的代码。 我正在寻找一种方法,我可以做到这一点,而无需两次查询数据库,这个我一直在使用的解决方案适用于小目的,但如果它被缩放,显然是不必要的数据库负载。 非常感谢

编辑:我转向PDO的原因是它的可移植性功能,因此 rowCount()并不适用于所有实例。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drj58429 2015-12-31 19:04

    You can use rowCount() method to get number of rows, like this:

    $result = $db->query("SELECT * FROM mytable");
    $count = $result->rowCount();
    echo $count;
    while($row = $result->fetch(PDO::FETCH_ASSOC)){
        // your code

    Here's the reference:


    In case you don't want to use rowCount() method, this is another way of doing it.

    $result = $db->query("SELECT * FROM mytable");
    $result_set = $result->fetchAll();
    $count = count($result_set);
    echo $count;
    while($row = array_shift($result_set)){
        // your code

    Here are the relevant references:

    点赞 打赏 评论
  • duanlangwen9597 2015-12-31 18:54

    In your case, there's no reason to perform a COUNT(*) query. You can just count how many rows were returned.

    $count = $result->fetchAll();

    Now $count holds reference to how many rows were returned.

    点赞 打赏 评论

相关推荐 更多相似问题