php的autocomplete,PHP MySQL autocomplete

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.

See script below:

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);

Upon selecting the correct user, I would like the user to de directed to page.php?id=$employee_id

Is this possible?

JavaScript

JavaScript

$(function() {

$( "#employees" ).autocomplete({

source: 'search.php'

});

});

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

As requested:

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:

$( "#employees" ).autocomplete({

source: 'search.php',

select: function( event, ui ) {

window.location.href = 'page.php?id='+ui.item.id;

}

});

Fiddle with console.log instead of location change: https://jsfiddle.net/dLe4a83x/

# Answer 2

Here you can use JQuery UI library to make navigation in autocomplete search Autocomplete search in PHP and Mysql. Here is the working code:

HTML form :

Javascript code:

`

$(function() {

$("#dd_user_input").autocomplete({

source: "global_search.php?cityId=28",

minLength: 2,

select: function(event, ui) {

var getUrl = ui.item.id;

if(getUrl != '#') {

location.href = getUrl;

}

},

html: true,

open: function(event, ui) {

$(".ui-autocomplete").css("z-index", 1000);

}

});

});

`

Here location href is mentioned so user can navigate upon clicking this link.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值