2013-05-18 80 views
0

我正在嘗試爲我的網站製作搜索腳本。目前爲止這一切都進展順利,但如果搜索結果不存在,我想顯示「沒有顯示結果」。我試過這個:如果數組爲空,PHP將顯示「無結果」

<?php 

while($resultsarray(mysql_fetch_assoc($searchresult))//$searchresult is the result of my MySQL query 
{ 
    if($_GET['options']=='user') { 
     echo "<a href = 'userinfo.php?id=".$resultsarray['usernum']."'>".$resultsarray['username']."</a>"; 
    } 
    else if($_GET['options']=='topics') { 
     echo "<a href = 'display_post.php?id=".$resultsarray['id']."'>".$resultsarray['subject']."</a>"; 
     echo "<p>".$resultsarray['content']."</p>"; 
    } 
} 

if(empty($resultsarray)) { 
    echo "<p>There are no results to display.</p>"; 
} 

但是總是顯示消息,即使有結果。我也試過這個:

<?php 

$resultsarray = mysql_fetch_assoc($searchresult); 
if(empty($resultsarray)) { 
    echo "<p>There are no results to display.</p>"; 
} 
while($resultsarray = mysql_fetch_assoc($searchresult))//$searchresult is the result of my MySQL query 
{ 
    if($_GET['options']=='user') { 
     echo "<a href = 'userinfo.php?id=".$resultsarray['usernum']."'>".$resultsarray['username']."</a>"; 
    } 
    else if($_GET['options']=='topics') { 
     echo "<a href = 'display_post.php?id=".$resultsarray['id']."'>".$resultsarray['subject']."</a>"; 
     echo "<p>".$resultsarray['content']."</p>"; 
    } 
} 

但是那也沒用。任何有關這個問題的幫助表示讚賞。

+0

做一個'var_dump($ resultsarray);' – GriffLab

回答

1

您可以使用mysql_num_rows()以確定有多少結果返回:

if (!mysql_num_rows($searchresult)) { 
    echo "<p>There are no results to display.</p>"; 
} 

在你現在的代碼,你失去的第一個結果行,因爲你在呼喚mysql_fetch_assoc()一次並丟棄結果。使用上面的方法,可以消除導致你失去一個結果行:

$resultsarray = mysql_fetch_assoc($searchresult); 

請注意,mysql_*功能已被棄用。請考慮更新您的代碼以使用mysqli_*PDO

+0

我知道mysql_ *,但這是一個包含很多頁面的家庭項目。說實話,我不能轉換它。 – imulsion

+0

優秀!謝謝。 – imulsion

+0

不用擔心mysql_。有些人不知道,並正在使用它的生產代碼,所以我把它作爲免費贈送。祝你的項目好運! –

3

試試這個:

if(! $resultsarray) { 
    echo "<p>There are no results to display.</p>"; 
}