【问题标题】:populate options for a drop down list from the database从数据库中填充下拉列表的选项
【发布时间】:2014-07-15 12:10:37
【问题描述】:

请考虑以下内容。这是我一直在尝试做的。 1)我有一个下拉列表,可用于选择学期。 2)一旦我选择了学期,该学期的课程应该出现在另一个下拉列表中。 3)随着学期的变化,课程也可能不得不改变。

我的数据库

course_info(courseID varchar(15) primary key,courseName varchar(30),semester int)

这是我使用 ajax、php 和 mysql 所做的。

我的 html 页面

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

<form>
<select name="users" onchange="showsemester(this.value)">
<option value="">Select a semester:</option>
<option value="1">Y i S i</option>
<option value="2">Y i S ii</option>

</select>
</form>
<br>
<div id="txtHint"><b>courses will be listed here.</b></div>
</body>

我的 php 页面

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

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


$sql="SELECT * FROM course_info WHERE semester = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table border='1'><tr><th>course ID</th><th>name</th><th>semester</th></tr>";

while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>". $row['courseID'] . "</td>";
  echo "<td>" . $row['courseName'] . "</td>";
  echo "<td>" . $row['semester'] . "</td>";
  echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

现在它以表格形式在 div 中生成结果,并且可以正常工作而没有任何错误。但我想将课程名称作为下拉列表中的选项,并将课程 ID 作为值。

非常感谢您在这方面给予的善意考虑。 谢谢你。 T

【问题讨论】:

  • 应该不难做到。你试过什么?
  • 我看不出问题出在哪里。您可以将数据放入表中...为什么不能用 做同样的事情

标签: php html mysql ajax


【解决方案1】:

你的php文件代码文件应该是这样的

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

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


$sql="SELECT * FROM course_info WHERE semester = '".$q."'";
$result = mysqli_query($con,$sql);
?>
<select name = "semester">
<?php
while($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['courseID']; ?>"><?php echo $row['courseName']; ?></option>
<?php
}
?>
</select>
<?php
mysqli_close($con);
?>

【讨论】:

  • 我需要在哪里添加这个?到 php 文件或 html 因为一开始我给它应该添加到 div txthint
  • 非常感谢。非常感谢您的贡献。这几天我一直在努力。再次感谢您。
猜你喜欢
  • 2010-09-17
  • 2011-11-09
  • 2014-12-25
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多