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 />";                  
        }
    }   
333

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.

$result = mysqli_query(...);
if (mysqli_num_rows($result) > 0) {
    $data = mysqli_fetch_assoc($result);
    ... echoes go here ...
}

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.

498

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 rowsmysqli_num_rows == 0 this means there are no rows returned

People are also looking for solutions to the problem: php - Form is not getting displayed in codeigniter.

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.