imulsion
imulsion

Reputation: 9040

PHP displaying "no results" if an array is empty

I am trying to make a search script for my website. It's all going well so far, but I want to display "There are no results to display" if there are no results from the search. I tried this:

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

But that always displayed the message, even if there were results. I also tried this:

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

But that didn't work either. Any help with this problem is appreciated.

Upvotes: 0

Views: 462

Answers (2)

George Cummins
George Cummins

Reputation: 28906

You can use mysql_num_rows() to determine how many results were returned:

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

In your current code, you lose the first result row because you are calling mysql_fetch_assoc() once and discarding the result. Using the method above, you can eliminate the line that causes you to lose one result:

$resultsarray = mysql_fetch_assoc($searchresult);

Be aware that the mysql_* function are deprecated. Please consider updating your code to use mysqli_* or PDO.

Upvotes: 1

user1823761
user1823761

Reputation:

Try this:

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

Upvotes: 3

Related Questions