0

Web サイトの検索スクリプトを作成しようとしています。ここまでは順調ですが、検索結果が無ければ「表示する結果がありません」と表示させたい。私はこれを試しました:

<?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>";
    }
}

しかし、それもうまくいきませんでした。この問題に関するヘルプは大歓迎です。

4

2 に答える 2

3

これを試して:

if(! $resultsarray) {
    echo "<p>There are no results to display.</p>";
}
于 2013-05-18T11:16:53.453 に答える
1

mysql_num_rows()返された結果の数を判断するために使用できます。

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

mysql_fetch_assoc()現在のコードでは、1回呼び出して結果を破棄しているため、最初の結果行が失われます。上記の方法を使用すると、1 つの結果を失う原因となっている行を削除できます。

$resultsarray = mysql_fetch_assoc($searchresult);

mysql_*この関数は非推奨であることに注意してください。mysqli_*またはPDOを使用するようにコードを更新することを検討してください。

于 2013-05-18T11:17:38.430 に答える