duanjia4097 2015-12-31 18:46
浏览 38
已采纳

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.

  • 写回答

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:

    Edited:

    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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历