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
<?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);
// the query was run successfully
// and it returned at least a result
if(is_resource($searchResult) && mysql_num_rows($result) > 0){
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);
} else{
echo 'No Results were found';
}
}
?>
You could count the number of elements in the array, and either continue with your implode or display the message you mentioned.
<?php
if(count($results) > 0){
echo implode($results);
}
else {
echo "No results were found.";
}
?>
You also really should not be using the mysql_* functions. Use either the improved version (mysqli_*) or PDO.
if (mysql_num_rows($searchResult) == 0) {
echo "some error message";
} else {
... process data
}
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{
/* At least one row has been found */
}
How about a simple counter in the while statement:
$i = 0;
while (condition) {
$i++;
do stuff;
}
if ($i ==0) {echo 'No results found';}
Create a MYSQL Connection and paste this code below
$sql="SELECT * FROM tablename WHERE columnname LIKE your variable or constant ";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count>=1){if result was found}
else {if result was not found}
?>