PHP Textbox Autocomplete from Database

Feb 28, 2022 . Admin



Hello Friends,

I am going to explain you example of PHP autofill textbox from database. You will learn PHP autocomplete textbox from database. In side this article we will see the php autofill form from database

This article will give you simple example of how to PHP autocomplete textbox from database example. We will use get search how to autocomplete textbox from database in PHP.

You can use from PHP jQuery autocomplete textbox from database. I will give you simple autocomplete textbox in jQuery and PHP from database.

So, let's see bellow solution:

index.php
<!doctype html>
<html lang="en">
<head>
    <!-- jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 
    <!-- jQuery UI -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
    <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 mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card w-75 m-auto">
                    <div class="card-header bg-info text-white text-center">
                        <h4 style="font-size: 20px;font-weight: bolder;">PHP Textbox Autocomplete from Database - Mywebtuts.com</h4>
                    </div>
                    <div class="card-body" style="height: 280px">
                        <div class="form-group">
                            <label><strong>Products :</strong></label>
                            <input type="text" autocomplete="off" name="city" id="search_city" placeholder="Type to search..." class="form-control">  
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
      $(function() {
         $( "#search_city" ).autocomplete({
           source: 'products.php',
         });
      });
    </script>
</body>
</html>
products.php
<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'shope';

$conn = mysqli_connect($dbhost, $dbuser, $dbpass , $db) or die($conn);

function products($conn , $term){   
    $query = "SELECT * FROM products WHERE name LIKE '%".$term."%' ORDER BY name ASC";
    $result = mysqli_query($conn, $query);  
    $data = mysqli_fetch_all($result,MYSQLI_ASSOC);
    return $data;   
}

if (isset($_GET['term'])) {
    $products = products($conn, $_GET['term']);
    $getProducts = array();
    foreach($products as $product){
        $getProducts[] = $product['name'];
    }
    echo json_encode($getProducts);
}

?>
Output:

It will help you...
#PHP