Auto search suggestion in php

15/04/2017   04:04:27 PM

Hello, in this tutorial I will explain auto complet textbox using php. Autocomplete textbox is very user friendly for web project. In this tutorial you can learn how to implement google like search textbox in PHP. Using jQuery we can easily display auto suggestion from the database under textbox.We fetch database data and display it in auto complete textbox as like google search box.

1) We need to include jQuery library, jQuery UI library and jQuery UI stylesheet.

 
<link rel="stylesheet" type="text/css" href="jquery.ajaxcomplete.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.ajaxcomplete.js"></script>
 

 

2) Define the autocomplete function and provide the source file.

 
<script>
$(document).ready(function(){
$("#country").autocomplete("ajaxcomplete.php", {
selectFirst: true
});
});
</script>
 

 

3) HTML

Just require the following HTML.

 
<label>Enter Your Country Name : </label>
<input name="country" type="text" id="country" size="20"/> 
 

 

4) Complete code of index.php page will look like following

<link rel="stylesheet" type="text/css" href="jquery.ajaxcomplete.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.ajaxcomplete.js"></script>
<script>
$(document).ready(function(){
$("#country").autocomplete("ajaxcomplete.php", {
selectFirst: true
});
});
</script>
</head>
<body>
<label>Enter Your Country Name : </label>
<input name="country" type="text" id="country" size="20"/>
</body>

 

5) Create PHP Source File ajaxcomplete.php

We can get the textbox value by q field ($_GET[q]) from the query string.

<?php

$q=$_GET['q'];

$my_data=$q;

$conn=mysql_connect('localhost','root','') or die("Database Error");

mysql_select_db('sampledb',$conn);

$sql="SELECT * FROM product WHERE name LIKE '%$my_data%' ORDER BY id LIMIT 10";

$result = mysql_query($sql) or die(mysql_error());

if($result)

{

while($row=mysql_fetch_array($result))

{

echo $row['name']."\n";

}

}

?>


Output

                   

Support us by Sharing