[英]PDO rowCount() works on MySQL but not in 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;
}
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"
}
SQL Server中的var_dump($ numrows)
int(-1)
MySQL中的var_dump($ numrows)
int(1)
問候。
我知道這是一個舊線程,但是今天早上我也遇到了類似的問題,而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);
當我想使用需要知道要返回的行數的查詢時(使用SQL Server),我使用PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL
作為PDO prepare函數的第二個參數,如下所示:
$rs = $connection->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
這是Microsoft網站上的示例: https : //msdn.microsoft.com/zh-cn/library/ff628154(v=sql.105).aspx
好吧,共享一個好的解決方案永遠不會太晚,
蒙特利爾的JonathanParent-Lévesque
只需引用手冊 :
如果關聯的PDOStatement執行的最后一條SQL語句是SELECT語句,則某些數據庫可能會返回該語句返回的行數。 但是, 並非對於所有數據庫都可以保證此行為,並且便攜式應用程序不應該依賴此行為 。
您實際上不需要此功能。 以及大多數其他代碼
$result = $this->dbConnect->prepare($sql);
$result->bindParam(':user',$this->data['username']);
$result->bindParam(':pass',$this->data['password']);
$result->execute();
$jsonLogin = $result->fetch(PDO::FETCH_ASSOC));
if ($jsonLogin) {
$jsonLogin['area'] = 'another';
return json_encode($jsonLogin);
}
是您所需的全部代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.