我有一个搜索输入,可以在您键入内容时从我的数据库中提取前10个结果,并消除那些在运行中不匹配的结果。我从使用Twitter typeahead JavaScript库的https://codeforgeek.com/2014/09/ajax-search-box-php-mysql/获得了这个例子。
我的问题是,我必须定义要搜索的列而不是在process-search.php中选择它。我需要的是从选择字段中选择一个表列,然后使用所选列填充搜索。我觉得我很接近,但到目前为止还没有奏效。
我已经注释了我尝试使用的查询和代码。 Alos我已经在html中留下了选择框。
任何帮助都会非常感谢。
的index.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>
搜索-的script.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
});
});
过程的search.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);
?>
答案 0 :(得分:0)
有点难看,但这应该有用
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();
})
});
过程的search.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);
?>