[英]Query does not return a result
我將基於 Web 的應用程序從 MySQLi 轉換為 PDO,因為我也想使用 Microsoft SQL-Server 作為數據庫。 PDO 與 MySQL 數據庫一起工作就像一個魅力。 現在我第一次用 MS-SQL 嘗試了它,但它沒有。 幾乎每個查詢都必須更新。 這是非常令人沮喪的。
下面的簡單代碼讓我抓狂:
$ComputerGUID = "5BEC3779-B002-46BA-97C4-19158C13001F";
$SqlSelectQuery = "SELECT computermapping.PrinterGUID,
case when computerdefaultprinter.PrinterGUID IS NOT NULL then 1 else 0 end AS isDefaultPrinter
FROM computermapping
LEFT JOIN computerdefaultprinter ON computerdefaultprinter.ComputerGUID = computermapping.ComputerGUID
AND computerdefaultprinter.PrinterGUID = computermapping.PrinterGUID
WHERE computermapping.ComputerGUID = :ComputerGUID";
$SqlStatement = $pdo->prepare( $SqlSelectQuery );
$SqlStatement -> bindValue( ":ComputerGUID", $ComputerGUID, PDO::PARAM_STR );
$SqlStatement->execute();
$SelectQueryNumRows = $SqlStatement->rowCount();
IF ( $SelectQueryNumRows > 0 ) {
$Data = $SqlStatement->fetchAll(PDO::FETCH_ASSOC);
} ELSE {
echo "The query did not return a result ...";
}
它與 MySQL 工作正常並返回結果。
使用 Microsoft SQL-Server 它得到NO RESULT 。 (查詢沒有返回結果...)
在 Microsoft SQL Server Management Studio 中運行相同的查詢也可以正常工作:
使用 SQL Server Profiler 運行代碼時監控查詢顯示如下:
正如手冊中提到的:
某些數據庫可能會返回該語句返回的行數。 但是,不能保證所有數據庫都具有此行為,並且不應依賴於可移植應用程序。
所以,你不應該使用rowCount
。 但是當您獲取所有數據時 - 使用它:
$SqlStatement->execute();
$Data = $SqlStatement->fetchAll(PDO::FETCH_ASSOC);
// in case of no data - empty array will be returned
if ($Data) {
// process $Data;
} else {
echo "The query did not return a result ...";
}
另請注意,如果出現錯誤, $Data
可能為false
,如果需要,您應該處理$Data
的此值。
對於大多數驅動程序, PDOStatement::rowCount()
不會返回受 SELECT 語句影響的行數。 But if you are using PHP Driver for SQL Server, as is mentioned in the documentation , if the last SQL statement executed by the associated PDOStatement was a SELECT statement, a PDO::CURSOR_FWDONLY cursor returns -1 and a PDO::CURSOR_SCROLLABLE cursor returns結果集中的行數。
您需要准備這樣的語句:
$SqlStatement = $pdo->prepare(
$SqlSelectQuery,
array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.