简体   繁体   中英

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

Is this is most effective way to check 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(); will return -1 and that will consider as a true value for the if statement.

mysqli_result::fetch_assoc() will always return either an array with data or null . Due to PHP's type juggling , an array filled with data is a "truey" value and null is "falsey". Which means you can safely use the result in the if operator

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. But an empty array is again equal to false and therefore the result can be used in the condition as well.

Does it have to be a boolean? I think you're looking for $results->num_rows;

$number_or_results = $results->num_rows;
if($number_or_results){
 // DO STUFF WITH RESULTS
}
else{
 // TELL USER THERE'S NO DATA
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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