How to create Autocomplete textbox in php ?
To Create a Autocomplete textbox in php do following easy steps:-
Step 1 :- Create a new database give name as email. Create a new table give name as a registration table. Registration table contain registeration id, user name and email address.
Step 2 :- Create a new folder in htdocs give name as a autocomplete. create a new file and save as a db.php. db.php page
contain following code for the make connection with database required for the autocomplete box.
db.php
<?php
//db.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "email"; // your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
// /echo 'Connected ....';
}
?>
Step 3 :- create a new file and save as auto.php. In these file write a
simple textbox code and give a id name to a textbox and also import cdn file link in header and write a jquery autocomplete function code as shown in below page auto.php
auto.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- jQuery UI -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<br/>
<label for="usr">Email ID:</label>
<input type="text" id="email" name="email" class="form-control" placeholder="To">
</div>
</form>
</div>
<script type="text/javascript">
$(function() {
$("#email").autocomplete({
source: 'search.php'
});
});
</script>
</body>
</html>
Step 4 :- Create a new page and save as a search.php
On these page we are passing email id as term and that term passing to a select query for matching and the matching result again pass to the function as json data.
search.php
<?php require "db.php"; ?>
<?php
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = mysqli_query($conn,"SELECT * FROM registration WHERE email LIKE '%".$searchTerm."%' ORDER BY email ASC");
while ($row = mysqli_fetch_array($query)) {
$data[] = $row['email'];
}
//return json data
echo json_encode($data);
?>
Output :-
Autocomplete Textbox |