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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配