Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 20, 2023 05:15
Show Gist options
  • Save code-boxx/888e5879ebd74b180a8a6264860c37a3 to your computer and use it in GitHub Desktop.
Save code-boxx/888e5879ebd74b180a8a6264860c37a3 to your computer and use it in GitHub Desktop.
PHP MYSQL Autocomplete

PHP MYSQL AUTOCOMPLETE

https://code-boxx.com/autocomplete-php-mysql/

NOTES

  1. Create a dummy database and import 1-users.sql.
  2. Change the database settings in 2b-search.php, 3b-search.php, 4b-search.php to your own.
  3. Access 2a-single.html, 3a-multiple.html, 4a-override.html in your browser – Use http:// and not file://.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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;
INSERT INTO `users` (`id`, `name`, `email`, `phone`) VALUES
(1, 'Jazz Doe', 'jazz@doe.com', '56973317'),
(2, 'Jane Doe', 'jane@doe.com', '40378541'),
(3, 'Rusty Terry', 'rusty@terry.com', '34614899'),
(4, 'Peers Sera', 'peers@sera.com', '13014383'),
(5, 'Jaslyn Keely', 'jaslyn@keely.com', '52154191'),
(6, 'Richard Breann', 'richard@breann.com', '58765281'),
(7, '诸葛猪哥', 'zhuge@thad.com', '11753471'),
(8, 'Tillie Sharalyn', 'tillie@sharalyn.com', '33989432'),
(9, '王啊狗', 'akow@adelaide.com', '56539890'),
(10, 'Coby Kelleigh', 'coby@kelleigh.com', '83788228'),
(11, 'Frank Doe', 'frank@doe.com', '87074336'),
(12, 'John Doe', 'john@doe.com', '55163490'),
(13, 'Jan Doe', 'jan@doe.com', '45310572'),
(14, 'Joe Doe', 'joe@doe.com', '48938630'),
(15, 'Joanne Doe', 'joanne@doe.com', '44101677'),
(16, 'Johan Doe', 'johan@doe.com', '28278966'),
(17, 'Charles Doe', 'charles@doe.com', '45800899'),
(18, 'Charlie Doe', 'charlie@doe.com', '32644564'),
(19, 'Apple Doe', 'apple@doe.com', '76438908'),
(20, 'Orange Doe', 'orange@doe.com', '47648224');
<!DOCTYPE html>
<html>
<head>
<title>JS Autocomplete</title>
<meta charset="utf-8">
<style>*{font-family:Arial, Helvetica, sans-serif;box-sizing:border-box}input{padding:10px}</style>
<!-- (A) AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
</head>
<body>
<!-- (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>
</body>
</html>
<?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) ;
<!DOCTYPE html>
<html>
<head>
<title>JS Autocomplete</title>
<meta charset="utf-8">
<style>
*{font-family:Arial, Helvetica, sans-serif;box-sizing:border-box}
#myForm{max-width:500px;padding:20px;background:#f2f2f2}
label,input,.acWrap{display:block;width:100%;box-sizing:border-box}
input{padding:10px} label{padding:10px 0}
</style>
<!-- (A) AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
</head>
<body>
<!-- (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>
</body>
</html>
<?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) ;
<!DOCTYPE html>
<html>
<head>
<title>JS Autocomplete</title>
<meta charset="utf-8">
<style>*{font-family:Arial, Helvetica, sans-serif;box-sizing:border-box}input{padding:10px}</style>
<!-- (A) AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
</head>
<body>
<!-- (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>
</body>
</html>
<?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) ;
/* (A) AUTOCOMPLETE WRAPPER */
.acWrap {
display: inline-block; /* Or block if you like */
position: relative;
}
/* (B) SUGGESTIONS */
.acWrap .acSuggest {
position: absolute;
top: 100%; left: 0;
z-index: 9;
width: 100%;
background: #fff;
border: 1px solid #eee;
display: none;
}
.acWrap .acSuggest {
list-style: none;
padding: 0;
margin: 0;
}
.acWrap .acSuggest li {
padding: 10px;
}
.acWrap .acSuggest li:hover {
background: #d9e7ff;
cursor: pointer;
}
var ac = {
// (A) PROPERTIES
now : null, // current "focused instance"
// (B) ATTACH AUTOCOMPLETE
// target : target field
// data : suggestion data (array), or url (string)
// post : optional, extra data to send to server
// delay : optional, delay before suggestion, default 500ms
// min : optional, minimum characters to fire suggestion, default 2
// select : optional, function to call on selecting an option
attach : inst => {
// (B1) SET DEFAULTS
if (inst.delay == undefined) { inst.delay = 500; }
if (inst.min == undefined) { inst.min = 2; }
inst.timer = null; // autosuggest timer
inst.ajax = null; // ajax fetch abort controller
// (B2) UPDATE HTML
inst.target.setAttribute("autocomplete", "off");
inst.hWrap = document.createElement("div"); // autocomplete wrapper
inst.hList = document.createElement("ul"); // suggestion list
inst.hWrap.className = "acWrap";
inst.hList.className = "acSuggest";
inst.hList.style.display = "none";
inst.target.parentElement.insertBefore(inst.hWrap, inst.target);
inst.hWrap.appendChild(inst.target);
inst.hWrap.appendChild(inst.hList);
// (B3) KEY PRESS LISTENER
inst.target.addEventListener("keyup", evt => {
// (B3-1) CLEAR OLD TIMER & SUGGESTION BOX
ac.now = inst;
if (inst.timer != null) { window.clearTimeout(inst.timer); }
if (inst.ajax != null) { inst.ajax.abort(); }
inst.hList.innerHTML = "";
inst.hList.style.display = "none";
// (B3-2) CREATE NEW TIMER - FETCH DATA FROM SERVER OR ARRAY
if (inst.target.value.length >= inst.min) {
if (typeof inst.data == "string") { inst.timer = setTimeout(() => ac.fetch(), inst.delay); }
else { inst.timer = setTimeout(() => ac.filter(), inst.delay); }
}
});
},
// (C) FILTER ARRAY DATA
filter : () => {
// (C1) SEARCH DATA
let search = ac.now.target.value.toLowerCase(),
complex = typeof ac.now.data[0]=="object",
results = [];
// (C2) FILTER & DRAW APPLICABLE SUGGESTIONS
for (let row of ac.now.data) {
let entry = complex ? row.D : row ;
if (entry.toLowerCase().includes(search)) { results.push(row); }
}
ac.draw(results.length==0 ? null : results);
},
// (D) AJAX FETCH SUGGESTIONS FROM SERVER
fetch : () => {
// (D1) FORM DATA
let data = new FormData();
data.append("search", ac.now.target.value);
if (ac.now.post) {
for (let [k,v] of Object.entries(ac.now.post)) { data.append(k,v); }
}
// (D2) FETCH
ac.now.ajax = new AbortController();
fetch(ac.now.data, { method:"POST", body:data, signal:ac.now.ajax.signal })
.then(res => {
ac.now.ajax = null;
if (res.status != 200) { throw new Error("Bad Server Response"); }
return res.json();
})
.then(res => ac.draw(res))
.catch(err => console.error(err));
},
// (E) DRAW AUTOSUGGEST OPTIONS
draw : results => { if (results == null) { ac.close(); } else {
// (E1) RESET SUGGESTIONS
ac.now.hList.innerHTML = "";
// (E2) DRAW OPTION
let complex = typeof results[0]=="object";
for (let row of results) {
// (E2-1) SET "DISPLAY NAME"
let li = document.createElement("li");
li.innerHTML = complex ? row.D : row;
// (E2-2) SET SUGGESTION DATA
if (complex) {
if (row.V) { li.dataset.val = row.V; }
let entry = {} , multi = false;
for (let [k,v] of Object.entries(row)) {
if (k!="D" && k!="V") { entry[k] = v; multi = true; }
}
if (multi) { li.dataset.multi = JSON.stringify(entry); }
}
// (E2-3) ON SELECTING THIS OPTION
li.onclick = () => ac.select(li);
ac.now.hList.appendChild(li);
}
ac.now.hList.style.display = "block";
}},
// (F) ON SELECTING A SUGGESTION
select : row => {
// (F1) SET VALUES
ac.now.target.value = row.dataset.val ? row.dataset.val : row.innerHTML;
let multi = null;
if (row.dataset.multi !== undefined) {
multi = JSON.parse(row.dataset.multi);
for (let i in multi) { document.getElementById(i).value = multi[i]; }
}
// (F2) CALL ON SELECT IF DEFINED
if (ac.now.select != null) { ac.now.select(row); }
ac.close();
},
// (G) CLOSE AUTOCOMPLETE
close : () => { if (ac.now != null) {
if (ac.now.ajax != null) { ac.now.ajax.abort(); }
if (ac.now.timer != null) { window.clearTimeout(ac.now.timer); }
ac.now.hList.innerHTML = "";
ac.now.hList.style.display = "none";
ac.now = null;
}},
// (H) CLOSE AUTOCOMPLETE IF USER CLICKS ANYWHERE OUTSIDE
checkclose : evt => { if (ac.now!=null && ac.now.hWrap.contains(evt.target)==false) {
ac.close();
}}
};
document.addEventListener("click", ac.checkclose);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment