我有一个搜索输入,可以在您键入时从我的数据库中提取前 10 个结果,并即时删除不匹配的结果。我从 https://codeforgeek.com/2014/09/ajax-search-box-php-mysql/那里得到了这个例子,它使用了Twitter typeahead JavaScript库。
我的问题是,我必须定义要搜索的列,而不是在进程搜索中选择它.php。我需要从选择字段中选择一个表列,然后使用所选列填充搜索。我觉得我很接近,但到目前为止还没有奏效。
我已经注释掉了我尝试使用的查询和代码,这些查询和代码位于有效的查询和代码下面。阿洛斯 我已经在 html 中留下了选择框。
任何帮助将非常感谢。
索引.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="../inc/js/typeahead.min.js"></script>
<script type="text/javascript" src="search-script.js"></script>
<div id="search-topic-group" class="dhl-group">
<label for="term">Search By:</label>
<select name="term">
<option value="">-- Select a Search Term --</option>
<option value="username">Username</option>
<option value="city">City</option>
</select>
</div>
<div id="group" class="dhl-group">
<label for="keyword">Enter a Keyword:</label>
<input type="text" name="keyword" class="typeahead tt-query" autocomplete="off" spellcheck="false" placeholder="Type your Query">
</div>
搜索脚本.js
// JavaScript Document
var col = 'country'
$(document).ready(function(){
"use strict";
//Type Ahead Functions for the Search
$('select[name="term"]').change(function(){
col = $('select[name="term"]').val();
});
$('input.typeahead').typeahead({
name: 'keyword',
remote:'process-search.php?key=%QUERY&col=' + col,
limit : 10
});
});
进程搜索.php
<?php
$key=$_GET['key'];
$col = $_GET['col']
//$term = $_GET['term'];
$array = array();
$errors = array();
$db = mysqli_connect(<HOST>,<UID>,<PWD>,<DB>);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "select * from table_name where ".$col." LIKE '%{$key}%'";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$array[] = $row[$col];
}
echo json_encode($array);
?>
有点丑,但这应该有效
Jquery:
var col = "default"; //Change it to whatever you want your column to default to.
$(document).ready(function(){
"use strict";
//Type Ahead Functions for the Search
$('input.typeahead').typeahead({
name: 'keyword',
remote:'process-search.php?key=%QUERY&col='+col,
limit : 10
});
//Grabs the currently selected column when it changes
$("select[name='term']").change(function(){
col = $("select[name='term']").val();
})
});
进程搜索.php
<?php
$key=$_GET['key'];
$col=$_GET['col'];
$array = array();
$errors = array();
$db = mysqli_connect(<HOST>,<UID>,<PWD>,<DB>);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "select * from table where ".$col." LIKE '%{$key}%'";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$array[] = $row['username'];
$array[] = $row[$term];
}
echo json_encode($array);
?>