[英]Is this the most effective way to check that there are values returned?
這是檢查fetch_assoc();
的最有效方法嗎? ?
$something_row = $something->get_result()->fetch_assoc(); // get result
if($something > 1){
// DO THIS
}else{
// DO THIS
}
我不知道任何其他方式,但這並不是檢查是否有返回值的最佳方式。
為什么我使用 1 是因為如果你說 if ($something == true){} 有時 fetch_assoc(); 將返回 -1 並將其視為 if 語句的真實值。
mysqli_result::fetch_assoc()
將始終返回帶有數據的數組或null
。 由於PHP 的 type juggling ,填充數據的數組是“truey”值,null 是“falsey”。 這意味着您可以安全地在if
運算符中使用結果
你不必添加任何特別的東西。 只需將結果值放在條件運算符中。
$something_row = $something->get_result()->fetch_assoc(); // get result
if($something_row) {
echo 'Yes, we have some values';
} else {
echo 'Nothing returned';
}
這同樣適用於mysqli_result::fetch_all
,但是這個 function 將始終返回一個數組,無論是否找到任何行。 但是空數組再次等於false
,因此結果也可以在條件中使用。
它必須是 boolean 嗎? 我認為您正在尋找$results->num_rows;
$number_or_results = $results->num_rows;
if($number_or_results){
// DO STUFF WITH RESULTS
}
else{
// TELL USER THERE'S NO DATA
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.