php - 扩展 AJAX 数据库查询的功能

标签 php html mysql ajax

您好,我正在处理以下代码,该代码与下拉列表一起工作,我希望将下拉列表替换为具有自动完成功能的文本框,其中包含数据库中的数据。

问题是,对于下拉列表,代码中已经有硬编码的选项可供选择,就像文本框一样,它应该根据数据库值生成每个选项。

我不知道如何做到这一点,任何帮助都会很棒:)

这是我目前的代码:

HTML:

<html>
<head>
<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;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html> 

PHP

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','l3tm31n','records');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"records");
$sql="SELECT * FROM workers WHERE id = '".$q."'";

$result = mysqli_query($con,$sql);

echo "<table border='1'>
<tr>
<th>name</th>
<th>age</th>
<th>address</th>
<th>hasCar</th>
<th>speaksForeignLanguage</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['hasCar'] . "</td>";
echo "<td>" . $row['speaksForeignLanguage'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?> 

最佳答案

将 mysql 查询更改为

从名称类似“%$q%”的 worker 中选择*

关于php - 扩展 AJAX 数据库查询的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23127985/

相关文章:

php - CakePHP基于子域选择数据库

php - 为什么我不应该在 PHP 中使用 mysql_* 函数?

php - htmlpurifier 不允许 css 重要声明

mysql - 改进 MySQL 查询性能

php - MySql:保存日期范围与保存单日

php - 检查 MySQL 连接

javascript - JQuery - 只需走进主要的 li 元素

python - 我的python代码输出错误的html数据

html - 如何阻止文本溢出 div

MySQL:如果列不存在,则更改表