Я полагаю, что вы можете вернуть метку и значение для автозаполнения:
В вашем PHP:
while($row = $stmt->fetch()) {
// add the ID inside () chars
$return_arr[] = [
'label' => $row['nome'],
'value' => $row['id']
];
}
В вашем JS:
$(function() {
$(".auto").autocomplete({
source: "search.php",
focus: function(event, ui) {
event.preventDefault();
// manually update the textbox
$(this).val(ui.item.label);
},
select: function(event, ui) {
event.preventDefault();
// manually update the textbox and readonly field
$(this).val(ui.item.label);
$("#other-input").val(ui.item.value);
}
});
});
ИЛИ: Вы можете попробовать ввести идентификатор в некоторые разделители, а затем удалить его перед отправкой в базу данных.Как то так:
if (isset($_GET['term'])){
// strip out the (ID) before searching in DB
$nomeOnly = preg_replace('/ \(.*\)/', '', $_GET['term']);
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM colaboradores WHERE nome LIKE :term');
$stmt->execute(array('term' => '%'.$nomeOnly.'%'));
while($row = $stmt->fetch()) {
// add the ID inside () chars
$return_arr[] = $row['nome'] . ' (' . $row['id'] . ')';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}