Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if the query results empty row mysqli [duplicate]

Tags:

php

mysql

mysqli

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>';
    }

}
like image 289
user3196424 Avatar asked Jan 21 '14 12:01

user3196424


People also ask

How do I check if Mysqli is empty?

For other successful queries mysqli_query() will return TRUE. The result can still be empty even if it was succesful. If you use pdo, as suggested above. You get an array back (empty array if result is empty) so you can do sizeof($array) or count($array) to check if you have 0 results or not.

How do you check if SQL result is empty in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

How do I find Mysqli query results?

The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.


1 Answers

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>';
        }
    }
}
like image 160
MacMac Avatar answered Sep 28 '22 05:09

MacMac