dongmaopiao0901 2009-05-19 15:12
浏览 34
已采纳

使用PDO进行行计数

There are many conflicting statements around. What is the best way to row count using PDO in PHP? Before using PDO, I just simply used mysql_num_rows.

fetchAll is something I won't want because I may sometimes be dealing with large datasets, so not good for my use.

Do you have any suggestions?

  • 写回答

22条回答 默认 最新

  • dongta1824 2009-05-19 15:16
    关注
    $sql = "SELECT count(*) FROM `table` WHERE foo = bar"; 
    $result = $con->prepare($sql); 
    $result->execute(); 
    $number_of_rows = $result->fetchColumn(); 
    

    Not the most elegant way to do it, plus it involves an extra query.

    PDO has PDOStatement::rowCount(), which apparently does not work in MySql. What a pain.

    From the PDO Doc:

    For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

    EDIT: The above code example uses a prepared statement, which is in many cases is probably unnecessary for the purpose of counting rows, so:

    $nRows = $pdo->query('select count(*) from blah')->fetchColumn(); 
    echo $nRows;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(21条)

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程