問題描述
如何在 PHP 中使用 PDO 檢查我的結(jié)果集是否為空?
How do I check if my result set is empty using PDO in PHP?
$SQL = "SELECT ......... ORDER BY lightboxName ASC;";
$STH = $DBH->prepare($SQL);
$STH->bindParam(':member_id', $member_id);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
$lightbox_name = $row['lightboxName'];
$lightbox_id = $row['lightboxID'];
echo '<option value="'.$lightbox_id.'">'.$lightbox_name.'</option>';
}
我以前是這樣做的:
$result = mysql_query("SELECT ...... ORDER BY lightboxName ASC;");
if(!$result) { echo 'No results found!'; }
但是剛剛開始使用 PDO 和準備好的語句并且檢查 $STH
似乎沒有按預期工作 - 它總是有價值的!
But have just started using PDO and prepared statements and checking against $STH
does not seem to work as expected — it always has value!
推薦答案
我會嘗試使用 rowCount()
:
I would try to use rowCount()
:
$rows_found = $STH->rowCount();
但是,根據(jù)手冊:
如果關聯(lián)的 PDOStatement 執(zhí)行的最后一條 SQL 語句是一條 SELECT 語句,某些數(shù)據(jù)庫可能會返回行數(shù)該語句返回.但是,不能保證此行為適用于所有數(shù)據(jù)庫,不應依賴于可移植應用程序.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
如果它不適合您,您可以使用手冊中提到的其他方法.
If it does not work for you, you can use the other method mentioned in the manual.
您當然也可以在 while
循環(huán)之前設置一個變量,在循環(huán)中更改它并檢查循環(huán)后的值...
You can of course also set a variable before your while
loop, change it in your loop and check the value after the loop...
這篇關于如何使用 PHP 的 PDO 檢查數(shù)據(jù)庫查詢返回的結(jié)果的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!