【发布时间】:2023-04-01 13:35:01
【问题描述】:
我想从数据库中获取数据并将它们显示到下拉列表中。因此,当我单击该选项时,它应该给我来自该数据库的结果。因此,如果我在数据库中手动添加一个新条目,我的选择选项应该会自动变大。
这是我的代码: index.html:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.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">here should be opt1 from db</option>
<option value="2">here should be opt1 from db</option>
<option value="3">here should be opt1 from db</option>
<option value="4">here should be opt1 from db</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
getuser.php
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','ajax');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$sql="SELECT * FROM users WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Vorname</th>
<th>Nachname</th>
<th>Alter</th>
<th>Stadt</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['vorname'] . "</td>";
echo "<td>" . $row['nachname'] . "</td>";
echo "<td>" . $row['r_alter'] . "</td>";
echo "<td>" . $row['stadt'] . "</td>";
echo "<td>" . $row['job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
我需要更改代码,以便选择字段(启动时)动态填充数据库中的当前值。
我希望你能帮助我...
谢谢!
【问题讨论】:
-
请阅读How to Ask。如果您想寻求我们的帮助,那么您需要具体了解您实际需要什么帮助。您显然已经知道如何从数据库中选择内容,以及如何遍历结果记录。那么,您现在的问题到底出在哪里,要做到这一点 a) 选择您需要的数据,然后 b) 在循环中从该数据中创建选项元素?
标签: javascript php html mysql ajax