Wednesday, April 13, 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.

<script type="text/javascript">
function showHint(str)
if (str.length==0)
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
Input Name : <input type="text" onkeyup="showHint(this.value)" size="20" />
<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');
$query = mysql_query(&quot;SELECT * FROM staff where name like '%$q%'&quot;);
&lt;table bgcolor=&quot;#000000&quot; cellspacing=&quot;1&quot; cellpadding=&quot;3&quot;&gt;
&lt;tr bgcolor=&quot;#DDDDDD&quot;&gt;
&lt;? while($row = mysql_fetch_object($query)): ?&gt;
&lt;tr bgcolor=&quot;#FFFFFF&quot;&gt;
&lt;? endwhile; ?&gt;
&lt;? }

So hopefully can help

No comments:

Post a Comment