我正在尝试从多个表中检索数据。所以当用户点击并选择一个项目时,php文件会从相应的表中检索数据。
这是我第一次使用 Ajax 尝试使用 w3 学校代码并尝试修改,我猜如果条件是问题我正在使用的方式?在我尝试使用多表之前,它起作用了。
我的脚本
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "Please Select type of users to view";
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_users.php?q="+str,true);
xmlhttp.send();
}
}
</script>
我的表单
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
</select>
</form>
我的 PHP 页面
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','X','X','X');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con);
if ($q='Admin')
{
$sql="SELECT * FROM admin";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Email</th>
<th>Name</th>
<th>Mobile</th>
<th>Address</th>
<th>Password</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
}
echo "</table>";
else if ($q='Staff')
{
echo "This is from Database B
}
else
{
echo "This is from database C";
}
mysqli_close($con);
?>
最佳答案
您正在使用 $q = intval($_GET['q']);
为您的分配分配一个字符串值。
intval()
“获取变量的整数值”
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
并使用 assignment而不是 comparison if ($q='Admin')
和 else if ($q='Staff')
都是字符串,而不是您选项中的整数。
应该按顺序读取 as and with 2 个等号 if ($q=='2')
和 else if ($q=='1')
以匹配您选择的数值选项。
或者,使用您的选项相应地更改它们以在值中读取为 Staff
和 Admin
(和 Customers
),同时删除 intval()
来自 GET 数组;选择权在您。
您也不需要 mysqli_select_db($con);
因为您已经在初始连接中声明了 4 个参数并且会因其他原因而失败;从技术上讲,您没有为其选择数据库。
您还缺少引号和分号(解析语法错误)
echo "This is from Database B
应该读作
echo "This is from Database B";
脚注:
我认为您基于自己的页面似乎是 http://www.w3schools.com/php/php_ajax_database.asp
如果是这样,那么我建议你完全按照他们的例子慢慢修改以适应你的需要。我本人曾成功地使用过该演示(在遥远的过去)。
他们的示例也使用了 WHERE
子句。
$sql="SELECT * FROM user WHERE id = '".$q."'";
编辑:仅作记录,此条件缺少大括号:
if ($q='Admin')
{
关于php - 使用 Ajax 和 mysql 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33313431/