Page 1 of 1

how to add a if else statment in the search function

Posted: Fri Feb 21, 2014 12:11 am
by chauhanRohit
hello every one, can any one help me with the searchbar.
i want to add a if else statment(or any other statement) so that if there is no search query , the search bar should not return anything.

currently the searchbar is returning the data even if there is no query(when the searchbar is empty and i press backspace


<?php
mysql_connect("localhost","root","") or die("could not connect");
mysql_select_db("test") or die("could not find database");
$output = '';

//collect
if(isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

$query = mysql_query("SELECT * FROM authors WHERE fname LIKE '%$searchq%' OR lname LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'there was no search result!';
}else{
while($row = mysql_fetch_array($query)){
$firstname = $row['fname'];
$lastname = $row['lname'];

$output .= '<div> '.$firstname.' '.$lastname.' </div>';
}

}
}
echo($output);

?>

Re: how to add a if else statment in the search function

Posted: Fri Feb 21, 2014 12:51 am
by requinix
Change your isset() to a !empty(). That'll also prevent a search for "0" from working, but I wouldn't figure that's an issue.

But you should also fix your Javascript thing so that it doesn't try to search when the text box is empty.

Re: how to add a if else statment in the search function

Posted: Sat Feb 22, 2014 1:48 am
by chauhanRohit
thannks for the quick reply, i am new to php and i dont understand what u mean
can u be a little more specific and help me edit the code.

Re: how to add a if else statment in the search function

Posted: Sat Feb 22, 2014 3:40 pm
by twinedev
Change this line:

Code: Select all

if(isset($_POST['searchVal'])){
to be:

Code: Select all

if (isset($_POST['searchVal']) && trim($_POST['searchVal')!='') {

Re: how to add a if else statment in the search function

Posted: Sun Feb 23, 2014 2:50 am
by chauhanRohit
than u so much sir.
one last thing can u help me with making the search results display as drop down list.

help anyone :(