php - mysqli_fetch_assoc - select on an empty table brings empty results instead of no result
627
The table exists but it's empty.
Having no data in the table, I await it does not echo anything and readsif ($notable1 == 'on')
, but it echoes.$from_month.
and the separators"| "
(The code works ok when the table does not exist.)
Where's the problem ? I do not find it .
foreach ($datesBooked_1_month as $value)
{
if ($result = mysqli_query($bdd, "SELECT * FROM `".$tab_from_month_year."` WHERE day = ".$value." "))
{
$data = (mysqli_fetch_assoc($result));
echo $data['day'].'/'`.$from_month.`"| ";
if ($data['roomtype_1'] <= 3) { echo $data['roomtype_1']."| " ;} else {echo "X| "; }
if ($data['roomtype_2'] <= 3) { echo $data['roomtype_2']."| " ;} else {echo "X| "; }
if ($data['roomtype_3'] <= 3) { echo $data['roomtype_3']."| " ;} else {echo "X| "; }
if ($data['roomtype_4'] <= 3) { echo $data['roomtype_4']."| " ;} else {echo "X| "; }
if ($data['roomtype_5'] <= 3) { echo $data['roomtype_5']."| " ;} else {echo "X| "; }
if ($data['roomtype_6'] <= 3) { echo $data['roomtype_6']."<br/>";} else{echo"X<br/>";}
}
else if (!$result){ $notable1 = 'on'; }
}
if ($notable1 == 'on')
{
foreach ($datesBooked_1_month as $value)
{
echo $value. "- Free #<br />";
}
}
Answer
Solution:
An empty result is still a valid result. You'll have to explicitly test for the presence of data before doing your echoes, e.g.
Note the use of mysqli_num_rows()
Your test is completely invalid.
$result
would only ever beFALSE
fs the query itself failed (syntax error, database not reachable, etc...). A query which results in no data is still a valid query result and will a proper result handle... that just happens to represent an empty set.Answer
Solution:
I think you shouldn't check the execution of the query
(!$result)
, because the query is actually executed so$result
will not be false as it happens in case table doesn't exists.You should just check returned rows
mysqli_num_rows == 0
this means there are no rows returned