PHP MySQL 自动完成 [英] PHP MySQL autocomplete

查看:49
本文介绍了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/

这篇关于PHP MySQL 自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆