[英]How to add autocomplete suggestions from database under search bar ?
I am new in web programming, so sorry if the following question seems silly. 我是Web编程的新手,如果以下问题看起来很愚蠢,请对不起。 I used JQuery to add auto complete under the search bar, but instead of using hard coded array as a source, I need data from database. 我使用JQuery在搜索栏下添加了自动完成功能,但是我不需要使用硬编码数组作为源,而是需要数据库中的数据。
Any help would be appreciated . 任何帮助,将不胜感激 。
<div class="navbar-form navbar-left">
<input class="form-control" placeholder="search..." name = "search" type="text"
autocomplete = off id = "autocomplete_search">
<script>
$( "#autocomplete_search" ).autocomplete
(
{
source: ["javascript", "java", "c++", "net", "web", "php"]
}
);
</script>
</div>
Use a function to get the data 使用函数获取数据
source: query()
Then the function would call the data. 然后该函数将调用数据。
function query(){
var q;
$.post('query.php', function(data){
q = data;
})
return q;
}
Then your PHP function would be: 那么您的PHP函数将是:
$data = array();
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$sql = "SELECT firstname FROM users";
foreach($conn->query($sql) as $row){
array_push($row['firstname'];
}
echo json_encode($data);
Then you'll have to play around with that. 然后,您必须尝试一下。 At least it's a start. 至少这是一个开始。
Here's a post on how to write a simple query. 这是有关如何编写简单查询的文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.