Here's an example. As you enter more letters of the name it narrows down the resulting list.
(first and last names are searched)
<?php
#
# HANDLE AJAX REQUESTS
#
if (isset($_GET['ajax'])) {
if ($_GET['ajax'] == 'names') {
$res = $pdo->prepare("SELECT id
, concat(fname, ' ', lname) as name
FROM person
WHERE fname LIKE ? OR lname LIKE ?
ORDER BY fname, lname
");
$res->execute([ $_GET['search'], $_GET['search'] ]);
$results = $res->fetchAll();
exit(json_encode($results));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<style type='text/css'>
</style>
<script type='text/javascript'>
$(function() {
$("#search").on("input",function() {
let srch = $(this).val() + "%"
$.get(
"",
{"ajax":"names", "search":srch},
function(resp) {
$("#person").html("")
$.each(resp, function(k,v) {
let opt = $("<option>", {"value":v.id, "text":v.name});
$("#person").append(opt);
})
},
"JSON"
)
})
})
</script>
</head>
<body>
<form>
Enter first part of name:
<input type='text' id='search' >
<br><br>
<select name='person_id' id='person' size='20'>
<!-- names returned from search go here -->
</select>
</form>