Nowadays, developers are searching for simple techniques to enhance better user experience in websites. Autosuggestion select box is a simple technique when compared to third party plugins. This feature gives pop up suggestions while you type one letter instead of a complete word. Now, letâs see how to implement this by using the HTML5Â <datalist>
 tag and by using PHP and MySQL to fetch data from the database.
The HTML5Â <datalist>
 element adds the feature like the select element. First, we should fetch the data from the database and then develop it to the <datalist>
 options. Letâs see how to do this.
Step 1: Connect to MySQL Database in PHP
First create a connection to MySQL database in PHP.
<?php
//connect to mysql database
$connection = mysqli_connect("localhost","username","password","databasename") or
die("Error " . mysqli_error($connection));
?>
Step 2: Fetch the Required Data from MySQL Table
Next, fetch the required MySQL table data from the database and then select the required names from the category table.
<?php
//fetch data from database
$sql = "select country_name from countries";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
?>
Note: country_name – category name, Countries – table name
Step 3: Create Datalist with MySQL Data
Next, create a <datalist>
 element by using resultset and then add the category name to the data options one by one.
<datalist id="countryname">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['country_name']; ?>"><?php echo $row['country_name']; ?> </option>
<?php } ?>
</datalist>
Step 4: Integrate Datalist with a Textbox
Next, create an input element and add up the list attribute to the datalistâs id. It simply connects the textbox with the datalist options and suggests the words when the user types any letter in that input box. Here, autocomplete = “off” element is used to disable the default autocomplete feature for browsers.
Step 5: Close the Database Connection
Finally, close the MySQL database connection.
<?php mysqli_close($connection); ?>
Here, check the complete Code for HTML5 Autosuggestion Select Box
<?php
//connect to mysql database
$connection = mysqli_connect("localhost","username","password","example") or die("Error " . mysqli_error($connection));
//fetch data from database
$sql = "select country_name from countries";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
?>
<!DOCTYPE html>
<html>
<head>
<title>Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example</title>
</head>
<body>
<label for="country">Country Name</label>
<input type="text" list="countryname" autocomplete="off" id="country">
<datalist id="countryname">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['country_name']; ?>"><?php echo $row['country_name']; ?></option>
<?php } ?>
</datalist>
<?php mysqli_close($connection); ?>
</body>
</html>
Share