我将使用简单的 ajax 从数据库中检索数据。作为我的代码,我正在获取输出,但是如果我要使用特定字母“a”进行搜索,它不会显示来自 db 的特定单词,而是显示所有包含字母“a”的名称
<style>
#main {
padding: 10px;
margin: 100px;
color: Green;
width: 365px;
}
#display_results {
color:#222222; padding:5px;
background: #eeeeee;
}
</style>
<script src="jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
$("#search_results").slideUp();
$("#button_find").click(function(event){
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this}, function(data){
$("#display_results").html(data);
})
}
</script>
<div id="main">
<form id="searchform" method="post">
<input type="text" name="search_query" id="search_query" placeholder="Enter Name" size="55">
</form>
<div id="display_results"></div>
</div>
搜索.php
<?php
$con=mysql_connect("localhost","root","")or die("unable to connect");
mysql_select_db("newdb",$con) or die("unable to select database");
$term = strip_tags(($_POST['searchit']));
$term = mysql_real_escape_string($term); // Attack Prevention
if($term=="")
echo "Enter Something to search";
else{
$query = mysql_query("select name from userdetail where name like '%{$term}%'");
$string = '';
if (mysql_num_rows($query)){
while($row = mysql_fetch_assoc($query)){
$string .= "<b><a href='#'>".$row['name']."</a></b> - ";
//$string .= $row['email']."";
$string .= "\n";
}
}else{
$string = "No matches found!";
}
echo $string;
}
?>
最佳答案
如果您只想要以该词开头的词,您只需要在该词后加上通配符即可。
$query = mysql_query("select name from userdetail where name like '$term%'");
关于php - 使用 php ajax 在将数据从数据库检索到搜索框时显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23361759/