When an users enter the data on the text field, Autocomplete features will provide some suggestion. By using these suggestion the users can easily fill the form. Today we will be using PHP, Ajax to do the autocomplete search. For this example we will be using the country name. So that when the users starts entering the word, autocomplete will starts showing the list of the country name. So that the user can easily select the country name from the list.

Search form

Now, let’s start by creating the database and table, which we will be using in our example:

Creating the Database and Table

Run the below query to create the database named country

CREATE DATABASE country;

Now, execute the following command to create the table named country inside your country database.

CREATE TABLE `country` (
`id` int(11) NOT NULL auto_increment,
`code` varchar(2) NOT NULL default '',
`name` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Now we need to populate our country table with the country name. You can add if you have one. I will provide all the code along with the sql file to populate the country table at the end of this page.

CREATING THE DBCONNECT FILE

After creating the table, we need to connect to the MySql server. We will write a PHP script to connect to the server. For that, let’s create a file named dbconnect.php and write the following code.

<?php  

$con = mysqli_connect('localhost','root','');
if (!$con) {
	die('Could not connect to server' .mysqli_error($con));
}

mysqli_select_db($con, 'country') or die('Database could not be connected' .mysqli_error($con));

?>


Don’t forget to replace the credentials according to your MySql setting. Otherwise, this code will not work.

CREATING THE VIEW PAGE

At first, let’s create a first page for our application. This page will contain the input field. So that when the users starts to enter the country name on the input field, the suggestion will appear.

Create a file named index.php and put the following code on it.

<!DOCTYPE html>
<html>
<head>
	<title>Live Search</title>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

	<!-- For using .autocomplete widget use the following script -->
	<script type="text/javascript" src="autocomplete/jquery-ui-1.12.1/jquery-ui.min.js"></script> 
	<link rel="stylesheet" href="autocomplete/ajax.googleapis.com.jquery_theme_1.10.1-ui.min.css" type="text/css" />

	<link rel="stylesheet" href="autocomplete/jquery-ui-1.12.1/jquery-ui.min.css">

	<style type="text/css">
		/* enable absolute positioning */
		.inner-addon {
		  position: relative;
		}

		/* style glyph */
		.inner-addon .glyphicon {
		  position: absolute;
		  padding: 10px;
		  pointer-events: none;
		}

		/* align glyph */
		.right-addon .glyphicon { right: 0px;}

		/* add padding  */
		.right-addon input { padding-right: 30px; }



		body {
		  margin: 10px;
		}
	</style>

</head>
<body>

	<div class="container-fluid">
		
		<div class="col-md-6 col-md-offset-3">
		<h1>Php Ajax Auto Complete Search</h1>
  		<div class="inner-addon right-addon">
      		<i class="glyphicon glyphicon-search"></i>
      		<input type="text" class="form-control" id="country" placeholder="Search" />
    	</div>
    	</div>

	</div>

</body>
</html>

Using the above code we have only created the simple input field where the users can perform input action. So, this input field doesn’t perform the search operation. So we need to add ajax part to perform the search operation.

On the same index.php file add the following script at the end.

<script type="text/javascript">
    $('#country').keyup(function(){
        var country = $(this).val();
        $('#country').autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: 'Search.php',
                    dataType: "json",
                    data: {
                        term: request.term,
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            minLength: 1,
            delay: 100
        });
    });
</script>

In our script we have call the Search.php file. So let’s create it.

Creating the Search Page

With ajax we will sent the keyword typed by users to the search.php file. We will use these keywords to search our database and return the result .

Create a file named search.php and place a following code on it.

<?php 

include 'dbconnect.php';

$term = mysqli_real_escape_string($con, $_REQUEST['term']);

if (isset($term) &amp;&amp; $term!='') {
		
		$return_arr = array();

		try{

			$sql = 'SELECT name FROM country WHERE name LIKE "%'.$term.'%" ';
			
			$result = mysqli_query($con, $sql);
			$rowCount = mysqli_num_rows($result);

			if ($rowCount > 0) {
				while ($row = mysqli_fetch_assoc($result)) {
					$return_arr[] = $row['name'];
				}
			}else{
				$return_arr[]="Data not found";
			}

		}catch(PDOException $e) {
	        echo 'ERROR: ' . $e->getMessage();
	    }

    /* Toss back results as json encoded array. */
    echo json_encode($return_arr);
}
?>

CONCLUSION

On this lesson, we build a Autocomplete Search using PHP, Ajax and MySql. You can add more complex logic, design and validations as per your requirements. If you wish to add to the discussion or would like to ask a question, then leave a comment below.

Download Source Code From Below

Comments

  1. You really make it seem really easy along with your presentation however I in finding this topic to be really something which I believe I’d never understand. It sort of feels too complicated and extremely huge for me. I’m looking ahead in your next put up, I will try to get the grasp of it!

Leave a Reply

Your email address will not be published. Required fields are marked *