Thursday, April 14, 2011

PHP and Javascript Autocomplete Search

Starting from the case when the search data using a key word table in a MySQL database. Search results can be done in several ways, but the accuracy and convenience take precedence. What is desired is to enter one character per word, it will display the results of database queries associated with that character.

Suppose we look for the word or the name of someone in a database, simply by memasukkam word Y, then Y is related to the word will be displayed in a list table: Yoyo, Sandy, Bayu and others. Next we discussed the script. In this case the language of php and javascript. Search techniques using javascript function showHint.


<head>
<script type="text/javascript">
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","search1.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<form>
Input Name : <input type="text" onkeyup="showHint(this.value)" size="20" />
</form>
<p><span id="txtHint"></span></p>

Save the script above with the name of search.php. Next create another php file with the name search1.php to invoke a MySQL database (database query) based on input from the file search.php

if (isset($_GET[q])) {
//load database from php
include ('../config/db_connect.php');
$q=$_GET[&quot;q&quot;];
$query = mysql_query(&quot;SELECT * FROM staff where name like '%$q%'&quot;);
?&gt;
&lt;table bgcolor=&quot;#000000&quot; cellspacing=&quot;1&quot; cellpadding=&quot;3&quot;&gt;
&lt;tr bgcolor=&quot;#DDDDDD&quot;&gt;
&lt;th&gt;ID&lt;/th&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;/tr&gt;
&lt;? while($row = mysql_fetch_object($query)): ?&gt;
&lt;tr bgcolor=&quot;#FFFFFF&quot;&gt;
&lt;td&gt;&lt;?=$row-&gt;ID?&gt;&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;&lt;?=$row-&gt;name?&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;? endwhile; ?&gt;
&lt;/table&gt;
&lt;? }

So hopefully can help
Read More