我想要一个从数据库表读取的动态选项列表,让我们说:学生,
必须向用户显示student_name
列表,当用户选择该列表时,必须将该学生的student_id
发送到数据库。例如:
Students table :
student_id student_name
----------------------------
1 John
2 Edward
在用户选项列表中必须只包含John,Edward ..但是当用户选择John时,选项选择器必须只将student_id('1')发送到数据库。
我当前的代码,但不是从db:S获取列表: 是的,这是我的代码,但由于某些原因它不起作用:
<select Name='student_id'>
<option value="">--- Select ---</option>
<?
mysql_connect ("localhost","root","");
mysql_select_db ("mydb");
$select="student_name";
if (isset ($select)&&$select!=""){
$select=$_POST ['student_name'];
}
?>
<?
$list=mysql_query("select * from students order by student_name asc");
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<? echo $row_list['student_id']; ?>"<? if($row_list['student_name']==$select){ echo "selected!"; } ?>>
<?echo $row_list['student_name'];?>
</option>
<?
}
?>
</select>
答案 0 :(得分:0)
尝试以下代码。
$con = mysqli_connect('localhost','root','','mydb');
$sql="SELECT student_id ,student_name FROM students";
$result = mysqli_query($con,$sql);
?>
<select name = "student">
<?php
while($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['student_id']; ?>"><?php echo $row['student_name']; ?></option>
<?php
}
?>
</select>
答案 1 :(得分:0)
这可能对你有所帮助
$result = mysqli_query($con,"SELECT * FROM Students");
echo "<select>";
while($row = mysqli_fetch_array($result)) {
echo "<option id=".$row['student_id'].">" . $row['student_name'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
答案 2 :(得分:0)
您应该从PHP中获取数据库,然后从中构建列表
//YOU MUST ADD YOUR DATABASE CONNECTION
mysql_connect('localhost','username','password');
mysql_select_db("dbname");
//HERE IS YOUR SQL REQUEST
$SQL_request = "SELECT * FROM `student_table`";
$req = mysql_query($SQL_request) or die(mysql_error().'<br/>'.$SQL_request);
echo '<select name = "students">';
while($result = mysql_fetch_assoc($req)){
echo '<option value="'.$result['student_id'].'">'.$result['student_name'].'</option>';
}
echo '</select>';
?>