简体   繁体   English

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

[英]How to get number of affected rows from a mssql query in php pdo

I am changing my php project from using mysql to mssql. 我正在将我的php项目从使用mysql更改为mssql。 when i use if ($query->rowCount() == 0) { with mysql it works well but with mssql i get a negative value which isnt correct. 当我使用if ($query->rowCount() == 0) {与mysql它运行良好,但与mssql我得到一个负值,这是不正确的。 So i tried to use $count = count($query->fetchAll()); 所以我试着使用$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 使用mssql,它给我一个类似于使用mysql时的正值,但我得到一个错误我正在使用PHP服务器的SQL驱动程序

Fatal error: Uncaught PDOException: SQLSTATE[IMSSP]: There are no more rows in the active result set. 致命错误:未捕获PDOException:SQLSTATE [IMSSP]:活动结果集中没有其他行。 Since this result set is not scrollable, no more data may be retrieved. 由于此结果集不可滚动,因此无法检索更多数据。

Need some help with this issue 需要一些帮助来解决这个问题

The documentation is clear about PDOStatement::rowCount . 文档清楚地说明了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. 如果关联的PDOStatement执行的最后一个SQL语句是SELECT语句,则PDO :: CURSOR_FWDONLY游标返回-1。 A PDO::CURSOR_SCROLL ABLE cursor returns the number of rows in the result set. PDO :: CURSOR_SCROLL ABLE游标返回结果集中的行数。

If you want to use rowCount() for SELECT statements, you need to use PDO::CURSOR_SCROLLABLE : 如果要对SELECT语句使用rowCount() ,则需要使用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()); 当你使用$count = count($query->fetchAll()); your result set is already fetched after $query->fetchAll() call. $query->fetchAll()调用后,您的结果集已经被提取。 If you try to call PDOStatement::fetch or PDOStatement::fetchAll methods, you'll get this error. 如果您尝试调用PDOStatement::fetchPDOStatement::fetchAll方法,则会出现此错误。

Try the next approach: 尝试下一种方法:

<?php

...
$result = $query->fetchAll(); 
$count = count($result);
foreach ($result as $row) {

}
...

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM