tatty27 tatty27 - 6 months ago 8
PHP Question

Can't detect empty result

Depending on whether any results are found or not I want to set a value to

$case_num
and store it in an array to pass back to an
AJAX
call using
json
. The code I am using works as expected if an entry is found but if there are no results the value passed back is simply null.

$sql = "SELECT * FROM cases WHERE name LIKE '%$serial%'
AND DATE(date_entered) = CURDATE()";

$result_case = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
$row = mysqli_fetch_array($result_case);

if(!empty($result_case)){
$case_id = $row['id'];
$case_num = $row['name'];
}else{
$case_num = 'not found';
}

$output_array = array(
'source' => $source,
'case_found' => $case_num
);

echo json_encode($output_array);

Answer

You should change your if condition

if($row)

Remember that mysqli_fetch_array will return NULL if there's no rows to fetch and mysqli_query returns a boolean based on if the query succeeded (as in generated no errors)

Comments