doulan3436 2019-03-14 12:42
浏览 514
已采纳

如何从php pdo中的mssql查询中获取受影响的行数

I am changing my php project from using mysql to mssql. when i use if ($query->rowCount() == 0) { with mysql it works well but with mssql i get a negative value which isnt correct. So i tried to use $count = count($query->fetchAll()); with mssql which gives me a positive value similar to when using mysql but i get an error I am using Php drivers for sql server

Fatal error: Uncaught PDOException: SQLSTATE[IMSSP]: There are no more rows in the active result set. Since this result set is not scrollable, no more data may be retrieved.

Need some help with this issue

  • 写回答

1条回答 默认 最新

  • duanfen7676 2019-03-14 13:11
    关注

    The documentation is clear about PDOStatement::rowCount.

    Returns the number of rows added, deleted, or changed. If the last SQL statement executed by the associated PDOStatement was a SELECT statement, a PDO::CURSOR_FWDONLY cursor returns -1. A PDO::CURSOR_SCROLL ABLE cursor returns the number of rows in the result set.

    If you want to use rowCount() for SELECT statements, you need to use PDO::CURSOR_SCROLLABLE:

    <?php  
    #
    $server = "server\instance,port";  
    $dbname = "database";
    $uid = "uid";  
    $pwd = "pwd";  
    
    # Connection
    $conn = new PDO("sqlsrv:server=$server ; Database = $dbname", $uid, $pwd);  
    
    # SELECT statement
    $query = "SELECT * FROM Table1";  
    $stmt = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));  
    $stmt->execute();  
    echo $stmt->rowCount();  
    
    # End
    $stmt = null;
    $conn = null;
    ?>   
    

    When you use $count = count($query->fetchAll()); your result set is already fetched after $query->fetchAll() call. If you try to call PDOStatement::fetch or PDOStatement::fetchAll methods, you'll get this error.

    Try the next approach:

    <?php
    
    ...
    $result = $query->fetchAll(); 
    $count = count($result);
    foreach ($result as $row) {
    
    }
    ...
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿