我想通过Ajax搜索MySQL数据库。 但结果表有很多记录。 所以我想通过重新搜索第一个搜索结果表来过滤结果表。
下面的代码是我的db.html(文件名)代码。
<script>
function showUser(str){
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
var selectedLang = document.getElementById('lang').value;
xmlhttp.open("GET","db_"+selectedLang+".php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="lang" id="lang" size="2" style="width:99px;">
<option value="co">한국어</option>
<option value="en">English</option>
<option value="af">Afrikaans</option>
</select>
<form>
<input type="text" name="FirstName" maxlength="20" onkeyup="showUser(this.value)">
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
我的PHP代码如下。请阅读
<?php
$q = htmlspecialchars($_GET['q']);
$con = mysqli_connect('localhost','root','autoset','my_db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM persons WHERE FirstName = '".$q."' or LastName = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
include 'db.html';
?>
但是,这个php代码“包含'db.html'”并不像我想的那样有用。 和 Q1。我不能保留第一个搜索结果,所以 Q2。我无法重新搜索第一个搜索结果。
我怎样才能克服这2个问题? 拜托,帮助我!
答案 0 :(得分:0)
进行ajax调用时创建会话。在该会话中存储数据库连接句柄。执行查询时,将结果保存在临时表中。然后,当您执行每次搜索时,首先查找临时表。如果存在,首先在那里搜索并将结果重新保存在另一个临时表中。根据用户的反馈,丢弃第一个或不丢弃。
重复此操作,直到获得所需的结果集。