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

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条)

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单