PHP MySQL 自动完成
我有一个自动完成搜索字段,当用户输入名称时,结果会显示在下拉列表中.
I have an auto complete search field which as the user types a name, th results are shown in the dropdown.
这一切正常,并按原样显示数据.
This all works fine, and shows the data as it should.
不过,我正在等待将每个结果设为链接,因此当显示结果时,用户可以单击正确的名称,然后将其带到他们的个人资料.
I am waiting to make each result a link however, so when the results are shown the user can click on the correct name and it will take them to their profile.
见下面的脚本:
<input type='text' id=employees class='form-control' size="80" placeholder="Search Employees by first or last name">
search.php
$searchTerm = $_GET['term'];
$sql = mysql_query ("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE '{$searchTerm}%' OR name_first LIKE '{$searchTerm}%' OR employee_id LIKE '{$searchTerm}%'");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = array (
'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
选择正确的用户后,我希望用户重定向到 page.php?id=$employee_id
Upon selecting the correct user, I would like the user to de directed to page.php?id=$employee_id
这可能吗?
JavaScript
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
JavaScript
<script>
$(function() {
$( "#employees" ).autocomplete({
source: 'search.php'
});
});
</script>
根据要求:
PHP:
$pdo = new \PDO('mysql:host=localhost;dbname=test', $user, $pass);
$searchTerm = $_GET['term'];
$stmt = $pdo->prepare("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE :search OR name_first LIKE :search OR employee_id LIKE :search");
$stmt->execute([':search' => $searchTerm.'%']);
$array = [];
while (false !== ($row = $stmt->fetch())) {
$array[] = [
'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',
'id' => $row['id'],
];
}
echo json_encode($array);
JavaScript:
JavaScript:
<script>
$( "#employees" ).autocomplete({
source: 'search.php',
select: function( event, ui ) {
window.location.href = 'page.php?id='+ui.item.id;
}
});
</script>
摆弄 console.log 而不是位置更改:https://jsfiddle.net/dLe4a83x/
Fiddle with console.log instead of location change: https://jsfiddle.net/dLe4a83x/