Tuesday, June 5, 2012

live search using HTML5 and PHP

note: i m afraid this little thing has no "practical" use. this is made just for fun. damn sundays! 
as you type into search box, related search options are shown to you as drop down list.
you can make your own live search which compares user search query to the data available in your database and shows suggestions. 
i have used HTML5 <datalist> Element in search form to get user query. go and read about it first here.
observed something? in <datalist> element ,<option > tag contains the value we need to suggest every time user types. we can get those value dynamically from our database.
<option value="anything"> //static value   
<option value="<?php echo $row["ptitle"];?>"> //dynamic value from DB using PHP
 here is the full code:
<section>
<form id="addentry" method="post" action="search.php">
<fieldset>
<legend>search</legend>
<label for="title">
<span>search for:</span>
</label>
<input list="post" id="squery" name="squery" autofocus/>
<datalist id="post">
<?php
$query = "SELECT ptitle FROM posts"; 
/*you can modify table and searching field accordingly.*/ 
$result = mysql_query($query);       
confirm_query($result);
while(($row = mysql_fetch_array($result)))
{?>
<option value="<?php echo $row["ptitle"];?>"> // getting value from DB
 <?php ?>
</datalist>
</fieldset>
<input type="submit" value="Search" />
</form>
here is the output i'm getting:

No comments:

Post a Comment