Aug 15 2017
Aug 15, 2017

Real-time search with PHP PDO and Ajax

Categorised in:

Real-time search is a very interesting and useful functionality which you can use on your website and in this tutorial we will build this functionality using PHP (PDO), Ajax and MySQL.

Make your website more user-friendly with real-time search.

To get started we should create a database and in that database we need t have a table. I use MySQL and my database's name is tutorial, the table's name is users. My table has 2 columns: id and name and I have four users inserted already.

Let’s create the first PHP file which is index.php. In this file we will call the JQuery library and we will have a little bit of CSS in the head section. In the body section we will have the JavaScript code which will to the magic of real-time functionality and then the field where the users will type the name they are looking for and bellow the field we will have a div id where the Ajax will show the result.

So, here you can see the HTML code we need to write in index.php file and bellow this code you can find the explanation for the JavaScript functions.

<html>
<head>
<title>Search</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style>
#show_up{
	width: 200px;
	height: 200px;
	border: 1px solid #ddd;
	display: none;
}
#show_up a{
	border-bottom: 1px solid #ddd;
	display: block;
	padding: 5px;
}
</style>
</head>
<body>
<script>
$(document).ready(function(e){
	$("#search").keyup(function(){
		$("#show_up").show();
		var text = $(this).val();
		$.ajax({
			type: 'GET',
			url: 'search.php',
			data: 'txt=' + text,
			success: function(data){
				$("#show_up").html(data);
			}
		});
	})
});
</script>
<input type="text" name="names" id="search" />
<div id="show_up"></div>
</body>
</html>

As you can see we have just HTML and JavaScript in this file. The JavaScript will be active right after the browser will load this file. We can understand this just looking at the first $(document).ready() function:

$(document).ready(function(e){

});

Once the page is loaded completely then there is another function which detects if somebody is typing anything in the HTML field. Pay attention to the HTML code where we have our field:

<input type="text" name="names" id="search" />

There is an id=”search”. So, the function bellow, keyup(), detects if somebody is typing anything in the field:

$("#search").keyup(function(){

})

If this function detected any characters in the field, then we want to change the display of our #show_up id by using the show() function. If you look at the CSS style tag you will see that the #show_up id has display: none; The show();  function will change the display from none to block.

$("#show_up").show();

After the  display is changed the JavaScript will assign the whole data from the HTML field to the text variable as in the line bellow:

var text = $(this).val();

The next step is sending the data to another PHP file which is search.php and to do that we use Ajax:

$.ajax({
	type: 'GET',
	url: 'search.php',
	data: 'txt=' + text,
	success: function(data){
		$("#show_up").html(data);
	}
});

Let’s create the search.php file. The code bellow has comments in it so you can understand how it works.

<?php
// create a new function
function search($text){
	
	// connection to the Ddatabase
	$db = new PDO("mysql:host=localhost;dbname=tutorial", 'root', '');
	// let's filter the data that comes in
	$text = htmlspecialchars($text);
	// prepare the mysql query to select the users 
	$get_name = $db->prepare("SELECT name FROM users WHERE name LIKE concat('%', :name, '%')");
	// execute the query
	$get_name -> execute(array('name' => $text));
	// show the users on the page
	while($names = $get_name->fetch(PDO::FETCH_ASSOC)){
		// show each user as a link
		echo '<a href="">'.$names['name'].'</a>';
		
	}
}
// call the search function with the data sent from Ajax
search($_GET['txt']);
?>

The final result should look like this:

So, anytime you type a new character in that field the JavaScript will send the data through Ajax to search.php file. In that file we have a query which selects the users, with the name we typed in the field, from the database. I made a Video tutorial using this code and if you want you can watch it on YouTube by clicking this link.

Thank you!