Simple Autocomplete With PHP MySQL (Free Download)

Welcome to a quick tutorial on how to create an autocomplete textbox with PHP and MySQL. Looking to add autocomplete features to a textbox? But it doesn’t make any sense to load an entire library and inflate the loading times. Well, here is a sharing of my autocomplete using only pure HTML and Javascript – It’s both simple and lightweight. Read on for the examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

PHP MYSQL AUTOCOMPLETE

All right, let us now get into the autocomplete example with PHP and MySQL.

 

PART 1) DUMMY DATABASE

1-users.sql
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `phone` varchar(24) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`),
  ADD KEY `name` (`name`);

ALTER TABLE `users`
  MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;

This is the dummy database that we are working with, should be self-explanatory.

  • id User ID, primary key.
  • name User’s full name.
  • email The email.
  • phone Telephone number.

 

 

PART 2) AUTOCOMPLETE SINGLE FIELD

2A) HTML & JAVASCRIPT

2a-single.html
<!-- (A) AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
 
<!-- (B) INPUT FIELD -->
<input type="text" id="dName">
 
<script>
// (C) ATTACH AUTOCOMPLETE TO INPUT FIELD
ac.attach({
  target: document.getElementById("dName"),
  data: "2b-search.php"
});
</script>

  1. Load the autocomplete Javascript and CSS. If you want the details, check out my other tutorial on the HTML Javascript autocomplete.
  2. The usual HTML input field.
  3. Lastly, call ac.attach() on page load to attach the autocomplete – Just specify the target input field and your data URL.

 

 

2B) PHP SEARCH

2b-search.php
<?php
// (A) CONNECT TO DATABASE - CHANGE TO YOUR OWN!
$dbhost = "localhost";
$dbname = "test";
$dbchar = "utf8mb4";
$dbuser = "root";
$dbpass = "";
$pdo = new PDO(
  "mysql:host=$dbhost;dbname=$dbname;charset=$dbchar",
  $dbuser, $dbpass, [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
 
// (B) DO SEARCH
$data = [];
$stmt = $pdo->prepare("SELECT `name` FROM `users` WHERE `name` LIKE ?");
$stmt->execute(["%".$_POST["search"]."%"]);
while ($r = $stmt->fetch()) { $data[] = $r["name"]; }
echo count($data)==0 ? "null" : json_encode($data) ;

Beginners, keep calm and look carefully. This script is actually super simple.

  1. Connect to the database. Just make sure that the PDO extension is enabled in your php.ini and change the settings to your own.
  2. The Javascript will send $_POST["search"] over. All we need is to search the database and output the results in a flat array  –  SELECT * FROM `table` WHERE `field` LIKE "%SEARCH%".

 

 

PART 3) AUTOCOMPLETE MULTIPLE FIELDS

3A) HTML & JAVASCRIPT

3a-multiple.html
<!-- (A) AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
 
<!-- (B) AUTOCOMPLETE MULTIPLE FIELDS -->
<form id="myForm">
  <label for="dName">Name</label>
  <input type="text" id="dName">
  <label for="dEmail">Email</label>
  <input type="email" id="dEmail">
  <label for="dTel">Tel</label>
  <input type="text" id="dTel">
</form>
 
<script>
// (C) ATTACH AUTOCOMPLETE TO INPUT FIELD
ac.attach({
  target: document.getElementById("dName"),
  data: "3b-search.php"
});
</script>

So how about choosing a single suggestion to fill up multiple fields? It’s pretty much the same with the HTML and Javascript – Just define your HTML fields, and attach the autocomplete on page load.

 

3B) PHP SEARCH

3b-search.php
<?php
// (A) CONNECT TO DATABASE - CHANGE TO YOUR OWN!
$dbhost = "localhost";
$dbname = "test";
$dbchar = "utf8mb4";
$dbuser = "root";
$dbpass = "";
$pdo = new PDO(
  "mysql:host=$dbhost;dbname=$dbname;charset=$dbchar",
  $dbuser, $dbpass, [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
 
// (B) DO SEARCH
$data = [];
$stmt = $pdo->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
$stmt->execute(["%".$_POST["search"]."%"]);
while ($r = $stmt->fetch()) { $data[] = [
  "D" => $r["name"], "dEmail" => $r["email"], "dTel" => $r["phone"]
]; }
echo count($data)==0 ? "null" : json_encode($data) ;

Yep, it’s the same old connect to the database, then do a SELECT search. The only difference here is the response:

  • D is the “display value” for the “main autocomplete field”. In this example, it is the user’s name.
  • Then, followed by as many FIELD-ID => VALUE as required. In this example, the email column will populate the dEmail field, and the phone column will fill up dTel.

 

 

PART 4) OVERRIDE SELECTED VALUE

4A) HTML & JAVASCRIPT

4a-override.html
<!-- (A) AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">

<!-- (B) INPUT FIELD -->
<input type="text" id="dUser">
 
<script>
// (C) ATTACH AUTOCOMPLETE TO INPUT FIELD
ac.attach({
  target: document.getElementById("dUser"),
  data: "4b-search.php"
});
</script>

Let’s say we have 2 users with the same name. To distinguish between them, we have to add the email to the suggestion list – But when the option is selected, we populate the field with the email only. There’s no difference in the HTML/Javascript once again, we only have to change the PHP output.

 

4B) PHP SEARCH

4b-search.php
<?php
// (A) CONNECT TO DATABASE - CHANGE TO YOUR OWN!
$dbhost = "localhost";
$dbname = "test";
$dbchar = "utf8mb4";
$dbuser = "root";
$dbpass = "";
$pdo = new PDO(
  "mysql:host=$dbhost;dbname=$dbname;charset=$dbchar",
  $dbuser, $dbpass, [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
 
// (B) DO SEARCH
$data = [];
$stmt = $pdo->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
$stmt->execute(["%".$_POST["search"]."%"]);
while ($r = $stmt->fetch()) { $data[] = [
  "D" => "{$r["name"]} ({$r["email"]})", 
  "V" => $r["email"]
]; }
echo count($data)==0 ? "null" : json_encode($data) ;

As you can see:

  • D The “display value” is now “NAME (EMAIL)”.
  • V But when the user selects the option, we populate the target field with the email only.

P.S. If you want to fill up multiple fields, you can output more FIELD_ID => VALUE as with the previous example.

 

 

EXTRAS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

INDEX FOR SEARCH PERFORMANCE

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`),
  ADD KEY `name` (`name`);

Notice how we set the email and name columns in the dummy table as keys? This is one small suggestion for you guys who are new – Index and set the searchable fields as keys. Just what does “indexing” do? Imagine a library without a catalog system… Searching for a book will involve looking through every shelf and book in the library.

It works the same way in a database. If we don’t have indices, the database will have to look through each and every entry to find the ones that we want. While indexing does take up a little more disk space, it will also greatly speed up and improve search performance.

 

SEARCH SECURITY

<?php
session_start();
if (!isset($_SESION["user"]) { exit(); }

Before the toxic troll things start to spit acid – These are only simple examples. In production systems, one would have added more security. For example, users need to log in for the autocomplete script to respond.

 

SEARCH MULTIPLE FIELDS & TABLES

Searching from multiple fields:

SELECT * 
FROM `users` 
WHERE `name` LIKE '%SEARCH%' 
OR `email` LIKE '%SEARCH'

Searching from multiple tables:

SELECT *
FROM `TABLE-A`
LEFT JOIN `TABLE-B`
ON `TABLE-A`.FIELD = TABLE-B.FIELD
WHERE `TABLE-A`.FIELD LIKE '%SEARCH%'
OR `TABLE-B`.FIELD LIKE '%SEARCH%'

Most importantly, master the use of SELECT and JOIN by yourself – Links below.

 

NON-ENGLISH LANGUAGES

Just a small note and reminder – If you are dealing with non-English languages, remember to add <meta charset="utf-8"> in the HTML <head>.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this short tutorial. I hope it has given you a kick start to your own project, and if you decide to use my vanilla auto-complete, please do remember to do your own CSS styles with it… It is really nothing but a skeleton.

If there is anything that you like to add to this guide, please feel free to comment below. Good luck and happy coding!

26 thoughts on “Simple Autocomplete With PHP MySQL (Free Download)”

  1. Incredibly helpful tutorial – THANK YOU! I’m trying to extend it ever so slightly, though, and I can’t figure out how to make this work…
    Use case: Say you have 2 people in the database with a relatively common name… you type in “Chris Dav” and the typeahead shows 2 rows of “Chris Davis”. In order to select the right one, the rows need to show not only the name but also the phone and the email so you can select the right row, thereby filling in the other fields correctly.
    It seems like I need a search field that isn’t associated with a single database field but I haven’t been able to make that work no matter what I’ve tried. Could you please point me in the right direction?

  2. Hi,
    I just unzipped the files and the only changes I made were to connect to the database with the sample tables on my computer.

    When I try to run the multiple field file, I get this error on line 80 in autocomplete.js:

    “SyntaxError: Unexpected token ‘<', "
    “… is not valid JSON”

    I didn’t change anything that should generate this error. I hope this is familiar to someone, and there’s a simple fix I’m overlooking.

    1. Cannot parse JSON could mean anything and whatever. Just do some simple troubleshooting:

      – Edit 3b-search.php, add $_POST["search"]="jaz", access it in the browser, and see if it does the search properly.
      – Edit 3a-multiple.html, use absolute URL data: "http://site.com/path/3b-search.php"

  3. Sorry for the bother.
    Thank you for this big help.
    But I have a question now: How can I put a data (“id” for example) in hidden field on the while you’re writing a name…

    Thanks and have an happy new year!

    @}-,-‘—–
    Gianfranco

    1. that’s how it works

      $stmt = $pdo->prepare(‘SELECT * FROM clienti WHERE nominativo LIKE :term OR cell LIKE :term’);
      $stmt->execute([‘term’ => “%”.$_POST[“search”].”%”]);

    2. Yes, it works. 😆 To clear things up a little – That is an SQL query, not PHP. But I see that you have done your own homework on “how to do proper PDO binding”. Well done!

  4. Finally!
    This snippet worked by me, to define encoding not in link connection ($pdo), but after that in this way ($pdo->exec(“set names utf8”);):

    $pdo = new PDO(
    “mysql:host=$dbhost;dbname=$dbname”,
    $dbuser, $dbpass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    $pdo->exec(“set names utf8”);
    // (B) DO SEARCH
    $data = [];

    PHP version: 7.4.33 and 10.3.37-MariaDB here

Leave a Comment

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