检查查询结果是否为空行mysqli

时间:2014-01-21 12:47:58

标签: php mysql mysqli

我正在使用此代码,但我不明白如何检查查询是否返回零行。我怎么检查呢?

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

}

2 个答案:

答案 0 :(得分:29)

您可以使用数据集上的num_rows来检查返回的行数。例如:

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

答案 1 :(得分:0)

如果数组看起来像这样[null]或[null,null]或[null,null,null,...]

你可以使用implode:

implode用于将数组转换为字符串。

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