Ajax PHP MySQL Search Example

Ajax PHP MySQL Search Example

PHP Ajax search with MySQL database example. Here you will learn how to implement ajax search in PHP with MySQL database.

Sometimes, we need to search for data without loading the whole page. This tutorial shows you how you can implement ajax live data search using a PHP mysql database. This tutorial shows you an easy way to live search with MySQL using Ajax.

PHP MySQL Live Search using jQuery From Database

Just follow the few below steps and easily implement live search in PHP MySQL using jQuery from database:

  • First Create a Database Connection File
  • Create an ajax search form
  • Create a PHP Script for Search to DB

1. First Create a Database Connection File

In this step, you will create a file name db.php and update the below code into your file.

The below code is used to create a MySQL database connection in PHP. When we insert form data into MySQL database, there we will include this file:

<?php
	$servername='localhost';
	$username='root';
	$password='';
	$dbname = "my_db";
	$conn=mysqli_connect($servername,$username,$password,"$dbname");
	  if(!$conn){
		  die('Could not Connect MySql Server:' .mysql_error());
		}
?>

2. Create an ajax search form

In this step, you need to create an ajax search form and update the below code into your ajax search form.

<!DOCTYPE html>
<html>
<head>
  <title>Ajax PHP MySQL Search Example | Tutsmake.com</title>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>  
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
         <h2>Search for users</h2>
         <input type="text" name="search" id="search" autocomplete="off" placeholder="search user name here....">
         <div id="output"></div>
      </div>           
    </div>
 </div>
 
  <script type="text/javascript">
    $(document).ready(function(){
       $("#search").keyup(function(){
          var query = $(this).val();
          if (query != "") {
            $.ajax({
              url: 'ajax-db-search.php',
              method: 'POST',
              data: {query:query},
              success: function(data){

                $('#output').html(data);
                $('#output').css('display', 'block');

                $("#search").focusout(function(){
                    $('#output').css('display', 'none');
                });
                $("#search").focusin(function(){
                    $('#output').css('display', 'block');
                });
              }
            });
          } else {
          $('#output').css('display', 'none');
        }
      });
    });
  </script>
</body>
</html>

3. Create a PHP Script for Search to DB

In this step, you need to create one file name ajax-db-search.php and update the below code into your file.

The below code is to search into a MySQL database table using an Ajax PHP script:

<?php
  require_once "connection.php";

  if (isset($_POST['query'])) {
    
    $query = "SELECT * FROM users WHERE name LIKE '{$_POST['query']}%' LIMIT 100";
    $result = mysqli_query($conn, $query);

  if (mysqli_num_rows($result) > 0) {
     while ($user = mysqli_fetch_array($result)) {
      echo $user['name']."<br/>";
    }
  } else {
    echo "<p style='color:red'>User not found...</p>";
  }

}
?>

Conclusion

In this tutorial, you have learned how to implement live search in PHP with MySQL database table using PHP code.

This is a very basic and easy example of ajax search into the MySQL database using PHP code.

Recommended PHP Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

3 replies to Ajax PHP MySQL Search Example

  1. Thank You. It helped me in my project

  2. Hello!!

    Simple question: When search how to make the names hyperlink so they can be linked back to profile pages?

    Thank ya!!

    • Hi Meka,

      When you iterate the data through the while loop. To wrap the data with an anchor tag inside the while loop.

Leave a Reply

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