1

我想创建动态选择列表。例如:我的数据库中有 5 个学生。我的目标是创建 5 个选择,并在每个选择中创建数据库中的所有学生。因此,如果用户在数据库中插入第 6 个学生,则页面应显示 6 个选择,并且在每个选择中显示 6 个学生的姓名。

我已经尝试使用此代码,但它只创建 1 个选择,包含 4 个学生(数据库中的第一个学生丢失)。

编码:

$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
while($result=mysqli_fetch_array($execute))
{
echo '<select name=student'.$i.'>';
echo '<option value="-1" >Choose student</option> <br/>';
while($res=mysqli_fetch_array($execute))
{
    echo '<option value='.$res["id_student"].'>'.$res["name"].'</option> <br/>';
}
echo '</select>';
$i++;
}
4

2 回答 2

2
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";

$i=1;
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++) {
    $select .= '<select name=student' . $j . '>';
    $select .= '<option value="-1" >Choose student</option> <br/>';
    while($result=mysqli_fetch_array($execute)) {
        $select .= '<option value=' . $res["id_student"].'>' .   $res["name"] . '</option>';
        $i++;
    }
    $select .= '</select>';
}
echo $select;

更新

在此期间

$select = '<select name=student' . $j . '>';
$select .= '<option value=' . $res["id_student"].'>' .   $res["name"] . 

用这个其他的改变这条线

$select = '<select name="student' . $j . '">';
$select .= '<option value="' . $res["id_student"]."'>' .   $res["name"] . 

我们错过了 value 和 select name 的双引号

于 2013-04-30T19:05:34.110 回答
0

问题解决了,我只需要在 for 循环中插入变量 $exe 和 $execute,所以在每次迭代后刷新 $result,否则它只会在第一个选择中打印选项...

代码:

$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";

$execute=mysqli_query($con,$exe);
$select = '';

for($j = 0; $j < mysqli_num_rows($execute); $j++) 
{
    $exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
    $execute=mysqli_query($con,$exe);

    $select .= '<select name=student' . $j . '>';
    $select .= '<option value="-1" >Choose student</option> <br/>';
    while($result=mysqli_fetch_array($execute)) 
    {
         $select .= '<option value=' . $res["id_student"].'>' .   $res["name"] . '</option>';
    }
    $select .= '</select>';
}
echo $select;
于 2013-04-30T21:12:01.280 回答