我试图进行实时的ajax搜索。当你说出一个单词时,它会像w3schools一样自动显示建议。但由于某种原因,我的索引文件和我的PHP没有交换数据值或我的数据库由于某种原因没有连接。我总是得到“没有找到国家”。你能检查代码是否有错误? 这是php文件:
<?php
include_once('dbconnect.php');
$q = intval($_GET['q']);
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
?>
这是我的index.php文件:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function showCountry(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","indexsearchquery.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input id="search-box" name="q" type="text" autocomplete="off" placeholder="Search country..." onchange="showCountry(this.value)" />
<input type='image' name='search' id="search-icon" value='Submit' src="search-icon.png" >
<p style="color:white;">Suggestions: <span id="txtHint" ></span></p>
答案 0 :(得分:0)
您的国家/地区名称不是整数。但你将它转换为intval
将你的php文件改为
include_once('dbconnect.php');
$q = $_GET['q']; //<-----remove intval
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
答案 1 :(得分:-1)
了解dbconnect.php文件的内容非常重要,因为它是包含数据库连接变量的文件。 检查你的MySQL服务器是否已启动并且所有变量都设置良好。