web-dev-qa-db-fra.com

vérifier si les résultats de la requête sont vides mysqli

J'utilise ce code, mais je ne comprends pas comment vérifier si la requête ne renvoie aucune ligne. Comment puis-je vérifier cela?

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

}
12
user3196424

Vous pouvez utiliser le num_rows du jeu de données pour vérifier le nombre de lignes renvoyées. Exemple:

$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>';
        }
    }
}
28
MacMac

si tableau ressemble à ceci [null] ou [null, null] ou [null, null, null, ...]

vous pouvez utiliser imploser:

implode est utilisé pour convertir un tableau en chaîne.

$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
}
0
shajji