检查查询结果是不是为空行mysqli [重复]

Posted

技术标签:

【中文标题】检查查询结果是不是为空行mysqli [重复]【英文标题】:check if the query results empty row mysqli [duplicate]检查查询结果是否为空行mysqli [重复] 【发布时间】:2014-02-11 01:49:30 【问题描述】:

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

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


【问题讨论】:

【参考方案1】:

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

你可以使用内爆:

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

【讨论】:

1.当不需要胶水时,可以省略胶水参数。 2.如果所有的值都是null/empty,那么这个检查将失败。【参考方案2】:

您可以在数据集上使用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>';
        
    

【讨论】:

但我认为最好使用一个 if (($results) && ($results->num_rows !== 0))

以上是关于检查查询结果是不是为空行mysqli [重复]的主要内容,如果未能解决你的问题,请参考以下文章

检查结构是不是为空[重复]

检查数组是不是为空[重复]

MySQLi PHP:使用 MySQLi 检查 SQL INSERT 查询是不是完全成功

React检查Const是不是为空[重复]

检查 JSON 响应数据是不是为空 [重复]

检查数组是不是为空,因此禁用按钮[重复]