how to add a if else statment in the search function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
chauhanRohit
Forum Newbie
Posts: 7
Joined: Thu Feb 20, 2014 11:28 pm

how to add a if else statment in the search function

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

?>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
chauhanRohit
Forum Newbie
Posts: 7
Joined: Thu Feb 20, 2014 11:28 pm

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

Post 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.
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

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

Post by twinedev »

Change this line:

Code: Select all

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

Code: Select all

if (isset($_POST['searchVal']) && trim($_POST['searchVal')!='') {
chauhanRohit
Forum Newbie
Posts: 7
Joined: Thu Feb 20, 2014 11:28 pm

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

Post 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 :(
Post Reply