Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

Displaying message when no results found in PHP MySQL search

0

138 views

I have a PHP search script which queries a MySQL database. Currently, when no results are displayed the script shows and error. How can I make it display a message like "No Results were found" when nothing is returned?

My PHP script is:

<?php

mysql_connect("localhost","username","password");
mysql_select_db("database");

if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%'  LIMIT 8";
$searchResult=mysql_query($searchSQL);

while ($row=mysql_fetch_assoc($searchResult)){
    $results[]="<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
}

echo implode($results);
}

?>

asked June 25, 2011 2:18 pm CDT
posted via StackOverflow

3 Answers

0
 
if (empty($results)) { 
    echo 'No results found'; 
}

answered June 25, 2011 2:23 pm CDT
0
 

You could also use the function mysql_num_rows, which will tell you the number of rows returned by your query.

$rows = mysql_num_rows($searchResult);
if($rows <= 0){
    /* Code if there are no rows */
}
else{
    /* More than one row has been found */
}

answered June 25, 2011 2:23 pm CDT
0
 
if (mysql_num_rows($searchResult) == 0) {
   echo "some error message"; 
} else { 
  ... process data
}

answered June 25, 2011 2:23 pm CDT

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions
No results found
February 14, 2011