Я использую typeahead на своей странице, он может отображать значение из базы данных, но значение будет дублироваться, например, значение — это отель, и он сохранит отель в базе данных. кто-нибудь знает решение?
index.php
<script src = "typeahead.min.js"></script>
<script>
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote:'search.php?key=%QUERY',
limit : 20
});
});
</script>
<td><input type = "text" name = "typeahead" class = "typeahead tt-query, cal_amount typeahead" autocomplete = "on" spellcheck = "false" value = "<?php echo $res['supplier'];?>"><input type = "hidden" value = "" name = "typeahead" /></td>
search.php
<?php
$key=$_GET['key'];
$array = array();
include_once("connection.php");
$query=mysqli_query($con, "select * from supplier where cname LIKE '%{$key}%'");
while($row=mysqli_fetch_assoc($query))
{
$array[] = $row['cname'];
}
echo json_encode($array);
mysqli_close($con);
?>
Я подстраиваюсь под один вопрос.
Кода, относящегося к вопросу, нет, потому что ни один из примеров не содержит оператора вставки.






Я использовал AJAX для выполнения PHP-скрипта, передав ввод поля Typeahead в качестве параметра запроса для обработки SELECT, чтобы получить данные для предложения автозаполнения. для получения более подробной информации вы можете перейти по ссылке ниже.
https://phppot.com/jquery/bootstrap-autocomplete-with-dynamic-data-load-using-php-ajax/
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src = "typeahead.js"></script>
<script>
$(document).ready(function () {
$('.typeahead').typeahead({
source: function (query, result) {
$.ajax({
url: "search.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
});
</script>
<td><input type = "text" name = "typeahead" class = "typeahead tt-query, cal_amount typeahead" autocomplete = "on" spellcheck = "false" value = ""><input type = "hidden" value = "" name = "typeahead" /></td>
search.php
<?php
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'test');
$sql = $conn->prepare("SELECT * FROM supplier WHERE cname LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["cname"];
}
echo json_encode($countryResult);
}
$conn->close();
?>
Решение 2 - Без ajax.
// Create connection
$conn = new mysqli("localhost", "root", "", "test");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query=mysqli_query($conn, "select * from supplier");
$data = '';
while($row=mysqli_fetch_assoc($query))
{
// SELECT to get data for the autocomplete suggestion
$data.= '"' .$row["cname"]. '",';
}
?>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src = "typeahead.js"></script>
<script>
$(document).ready(function(){
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var data = [<?php echo rtrim($data, ',');?>
];
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
source: substringMatcher(data)
});
});
</script>
<input type = "text" name = "typeahead" class = "typeahead tt-query, cal_amount typeahead" autocomplete = "on" spellcheck = "false" value = ""><input type = "hidden" value = "" name = "typeahead" />
Спасибо, это работает для меня, я пытаюсь отредактировать код, который может отображать другие данные из того же идентификатора в другом столбце td, например, значением является название отеля, а другой столбец для отображения цены номера для этот отель
Пожалуйста, не задавайте несколько вопросов в одном посте. Затрудняет ответ, принятие ответа и поиск.