Autocomplete Search, Autocomplete From Database in PHP. We will understand how to implement an autocomplete search, in the PHP MySQL database using jQuery.


Here, we will implement an autocomplete search textbox in PHP MySQL Using jQuery and Bootstrap with a live demo example.


Sometimes, We need to search for data without loading the page. This tutorial shows you how to use an autocomplete search box in PHP MySQL with jQuery and bootstrap search form. 


Follow few steps to complete autocomplete search form: 


Step 1:

connect to Database -  We will create a file name db.php and update the below code into your project.

<?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());
        }
?>


Step 2:

Write html Form for search input box

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Autocomplete Search Box in PHP MySQL</title>
 
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
 
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <!-- Bootstrap Css -->
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body> 
<div class="container">
  <div class="row">
     <h2>Search Here</h2>
     <input type="text" name="search" id="search" placeholder="search here...." class="form-control">  
  </div>
</div>
<script type="text/javascript">
  $(function() {
     $( "#search" ).autocomplete({
       source: 'ajax-db-search.php',
     });
  });
</script>
</body>
</html>

Step 3:

include the database file abd write the query to search data from database

<?php
require_once "db.php";
if (isset($_GET['term'])) {
     
   $query = "SELECT * FROM users WHERE name LIKE '{$_GET['term']}%' LIMIT 25";
    $result = mysqli_query($conn, $query);
 
    if (mysqli_num_rows($result) > 0) {
     while ($user = mysqli_fetch_array($result)) {
      $res[] = $user['name'];
     }
    } else {
      $res = array();
    }
    //return json res
    echo json_encode($res);
}
?>


I hope it can help you...