PDO rowCount()在MySQL上有效,但在SQL Server 2008 R2中不可用

Sol*_*orp 0 php mysql pdo rowcount sql-server-2008-r2

当我在SQL Server 2008中获得行数时遇到问题,因为我的代码使用MySQL可以正常运行,但在SQL Server中却不能。

$sql = "SELECT TOP 1 U.Id , U.Name, U.Profile,  P.Name NameProfile
        FROM sa_users U
        INNER JOIN sa_profiles P ON P.Id = U.Profile
        WHERE User = :user  AND Pass = :pass";

$result = $this->dbConnect->prepare($sql) or die ($sql);
$result->bindParam(':user',$this->data['username'],PDO::PARAM_STR);
$result->bindParam(':pass',$this->data['password'],PDO::PARAM_STR);

if (!$result->execute()) {
    return false;
}

$numrows = $result->rowCount();
$jsonLogin = array();

var_dump($numrows);

if($numrows > 0) {
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $jsonLogin = array( 
            'name' => $row['Name'],
            'id' => $row['Id'],
            'profile' => $row['Profile'],
            'n_profile' => $row['NameProfile']
        );
    }

    $jsonLogin['area'] = 'another';
    return $jsonLogin;
} else {
    return false;
}
Run Code Online (Sandbox Code Playgroud)

MySQL和SQL Server中的var_dump($ result-> fetch())

array(8) {
["Id"]=>
string(1) "1"
[0]=>
string(1) "1"
["Nombre"]=>
string(13) "Administrador"
[1]=>
string(13) "Administrador"
["Perfil"]=>
string(1) "1"
[2]=>
string(1) "1"
["NomPerfil"]=>
string(13) "Administrador"
[3]=>
string(13) "Administrador"
}
Run Code Online (Sandbox Code Playgroud)

SQL Server中的var_dump($ numrows)

int(-1)
Run Code Online (Sandbox Code Playgroud)

MySQL中的var_dump($ numrows)

int(1)
Run Code Online (Sandbox Code Playgroud)

问候。

Jon*_*que 5

我知道这是一个旧线程,但是今天早上我也遇到了类似的问题,实际上该rowcount()函数可以使用SQL Server。

我正在使用这样的连接字符串(以连接到SQL Server数据库):

$connection = new PDO("sqlsrv:Server=" . $this->sourceServer . ";Database=" . $this->sourceDB, $this->sourceUser, $this->sourcePW);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Run Code Online (Sandbox Code Playgroud)

当我想使用需要知道要返回的行数的查询时(使用SQL Server),我将PDO::ATTR_CURSOR => PDO::CURSOR_SCROLLPDO prepare函数用作第二个参数,如下所示:

$rs = $connection->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
Run Code Online (Sandbox Code Playgroud)

这是Microsoft网站上的示例:https : //msdn.microsoft.com/zh-cn/library/ff628154(v=sql.105).aspx

好吧,共享一个好的解决方案永远不会太晚,

蒙特利尔的JonathanParent-Lévesque