简体   繁体   English

这是检查是否有返回值的最有效方法吗?

[英]Is this the most effective way to check that there are values returned?

Is this is most effective way to check fetch_assoc();这是检查fetch_assoc();的最有效方法吗? ? ?

$something_row = $something->get_result()->fetch_assoc(); // get result 

if($something > 1){
 // DO THIS
}else{
 // DO THIS
}

I don't know of any other way but this just doesn't feel like the best way to check if there are values returned.我不知道任何其他方式,但这并不是检查是否有返回值的最佳方式。

Why I use 1 is because if you say if ($something == true){} sometimes the fetch_assoc();为什么我使用 1 是因为如果你说 if ($something == true){} 有时 fetch_assoc(); will return -1 and that will consider as a true value for the if statement.将返回 -1 并将其视为 if 语句的真实值。

mysqli_result::fetch_assoc() will always return either an array with data or null . mysqli_result::fetch_assoc()将始终返回带有数据的数组或null Due to PHP's type juggling , an array filled with data is a "truey" value and null is "falsey".由于PHP 的 type juggling ,填充数据的数组是“truey”值,null 是“falsey”。 Which means you can safely use the result in the if operator这意味着您可以安全地在if运算符中使用结果

You don't have to add anything special.你不必添加任何特别的东西。 Simply put the resulting value in a conditional operator.只需将结果值放在条件运算符中。

$something_row = $something->get_result()->fetch_assoc(); // get result 

if($something_row) {
    echo 'Yes, we have some values';
} else {
    echo 'Nothing returned';
}

The same applies tomysqli_result::fetch_all , but this function will always return an array, no matter if any rows were found or not.这同样适用于mysqli_result::fetch_all ,但是这个 function 将始终返回一个数组,无论是否找到任何行。 But an empty array is again equal to false and therefore the result can be used in the condition as well.但是空数组再次等于false ,因此结果也可以在条件中使用。

Does it have to be a boolean?它必须是 boolean 吗? I think you're looking for $results->num_rows;我认为您正在寻找$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM