2014-01-21 94 views
10

我是mysqli的新手,我使用了我朋友的這段代碼,但我不明白如何檢查查詢是否返回zeo行。這是我的代碼。提前致謝。檢查查詢結果是否爲空行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>'; 
    } 

} 

回答

22

您可以使用數據集上的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>'; 
     } 
    } 
} 
+0

謝謝!那工作! – user3196424

+2

但我認爲最好使用一個如果: if(($ results)&&($ results-> num_rows!== 0)){ –

0

如果數組是這樣的[空]或[NULL,NULL]或[NULL,NULL,NULL,...]

您可以使用破滅:

破滅用於將數組轉換爲字符串。

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