Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying message when no results found in PHP MySQL search

Tags:

html

sql

php

mysql

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);
}

?>
like image 347
Callum Whyte Avatar asked Jun 25 '11 19:06

Callum Whyte


People also ask

How check query result is empty in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.

What does Mysql_query do in MySQL?

mysql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mysql_connect() was called with no arguments, and use it.

Which PHP function Retrives the text of a MySQL error message?

Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text.

WHERE condition use in php?

The WHERE clause is used to filter records. The WHERE clause is used to extract only those records that fulfill a specified condition.


2 Answers

if (empty($results)) { 
    echo 'No results found'; 
} else {
    echo implode($results);
}
like image 197
Sjoerd Avatar answered Sep 29 '22 09:09

Sjoerd


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}

?>
like image 29
Heart Avatar answered Sep 29 '22 07:09

Heart