在PHP中使用HTML添加下拉菜单 - 从mysql数据库填充

时间:2014-10-14 09:54:13

标签: php html mysql drop-down-menu

我正在尝试添加从mysql数据库填充的下拉菜单。这是我的代码:

$sql=  "SELECT id, course_period_id from schedule WHERE STUDENT_ID='$_SESSION[student_id]'";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
    $id=$row["id"];
    $course_period_id=$row["course_period_id"];
    $options.="<OPTION VALUE=\"$course_period_id\">".$course_period_id.'</option>';
}
echo '</TD></TR></TABLE>';
echo '<SELECT>
                <OPTION VALUE=0>Choose
                <?=$options?>
                </SELECT> ';

问题是它给了我一个零选项的下拉菜单。那么我的代码应该改变什么呢?

由于

4 个答案:

答案 0 :(得分:1)

以下代码应该可行。

    $sql=  "SELECT id, course_period_id from schedule WHERE STUDENT_ID='".$_SESSION[student_id]."'";
    $result=mysql_query($sql);

    $options="";

    while ($row=mysql_fetch_array($result)) {

        $id=$row["id"];
        $course_period_id=$row["course_period_id"];
        $options.="<OPTION VALUE=\"$course_period_id\">".$course_period_id.'</option>';
    }

    echo '</TD></TR></TABLE>';
    echo '<select>
        <option value="0">Choose</option>' . $options . '</select>';            

您没有正确联系PHP变量。

不能用于任何eco / print语句。事实上,它本身就是一个PHP代码,只能单独使用。

Ex - 在新的php页面中你可以这样做

<select>
<option value="0">Choose</option>
<?=$options?> 
Suggested way is
<?php echo $options; ?>
</select>

答案 1 :(得分:0)

为什么在php标签打开时使用php标签?

echo "<select>
      <option value=0>Choose</option>
      $options
      </select>";

答案 2 :(得分:0)

  

您是否检查过会话是否已设置会话!如果已设置,请确保您的会话ID与您的表列匹配。

答案 3 :(得分:0)

    Try this
$sql=  "SELECT id, course_period_id from schedule WHERE STUDENT_ID='$_SESSION[student_id]'";
        $result=mysql_query($sql);

        $options="";

        while ($row=mysql_fetch_array($result)) {

            $id=$row["id"];
            $course_period_id=$row["course_period_id"];
            $options.="<OPTION VALUE='".$course_period_id."'>".$course_period_id."</option>";
        }
?>
       <SELECT>
            <OPTION VALUE="0" selected>Choose</option>
             <?php echo $options;?>
            </SELECT>