18

I am using this code, but I don't understand how to check if the query returns zero rows. How can I check that?

$results = $mysqli->query("SELECT ANNOUNCE_NUMBER,ANNOUNCEMENTS,ANNOUNCE_TYPE,POST_DATE FROM home WHERE ANNOUNCE_NUMBER NOT LIKE $excludewelcome AND ANNOUNCE_NUMBER NOT LIKE $excludenews ORDER BY ANNOUNCE_NUMBER DESC LIMIT $position, $items_per_group");
if ($results) { 
    //output results from database

    while($obj = $results->fetch_object())
    {
        if($obj->ANNOUNCE_TYPE=='NEWSEVENTS')
        {
            $realstring='News and Events';
        }
        else
        {
        $realstring='Welcome Note';
        }

        echo '<li id="item_'.$obj->ANNOUNCE_NUMBER.'"><strong>'.$realstring.'</strong></span>';
        echo '<br \>'; 
        echo '('.$obj->POST_DATE.' ) <span class="page_message">'.$obj->ANNOUNCEMENTS.'</span></li>';
    }

}
Don't Panic
  • 39,820
  • 10
  • 58
  • 75
user3196424
  • 517
  • 2
  • 8
  • 16

2 Answers2

36

You can use the num_rows on the dataset to check the number of rows returned. Example:

$results = $mysqli->query("SELECT ANNOUNCE_NUMBER,ANNOUNCEMENTS,ANNOUNCE_TYPE,POST_DATE FROM home WHERE ANNOUNCE_NUMBER NOT LIKE $excludewelcome AND ANNOUNCE_NUMBER NOT LIKE $excludenews ORDER BY ANNOUNCE_NUMBER DESC LIMIT $position, $items_per_group");
if ($results) { 

    if($results->num_rows === 0)
    {
        echo 'No results';
    }
    else
    {
        //output results from database
        while($obj = $results->fetch_object())
        {
            if($obj->ANNOUNCE_TYPE=='NEWSEVENTS')
            {
                $realstring='News and Events';
            }
            else
            {
            $realstring='Welcome Note';
            }

            echo '<li id="item_'.$obj->ANNOUNCE_NUMBER.'"><strong>'.$realstring.'</strong></span>';
            echo '<br \>'; 
            echo '('.$obj->POST_DATE.' ) <span class="page_message">'.$obj->ANNOUNCEMENTS.'</span></li>';
        }
    }
}
MacMac
  • 32,380
  • 54
  • 146
  • 219
-2

if array is look like this [null] or [null, null] or [null, null, null, ...]

you can use implode:

implode is use for convert array to string.

$con = mysqli_connect("localhost","my_user","my_password","my_db");
$result = mysqli_query($con,'Select * From table1');
$row = mysqli_fetch_row($result);
if(implode(null,$row) == null){
     //$row is empty
}else{
     //$row has some value rather than null
}
shajji
  • 15
  • 1
  • 1. When no glue is desired, the glue parameter can be omitted. 2. If all of the values are null/empty, then this check will fail. – mickmackusa Oct 29 '20 at 08:44