doumu6941
2014-10-14 09:54
浏览 209
已采纳

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

I'm trying to add a drop down menu populated from mysql database. Here is my code:

$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> ';

The problem is that it gives me a drop down menu with zero options. So what should I change in my code?

Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • duanqiang5722 2014-10-14 09:55
    已采纳

    Why using php tag when php tags are already open?

    echo "<select>
          <option value=0>Choose</option>
          $options
          </select>";
    
    点赞 评论
  • drus40229 2014-10-14 09:59

    Following code should work.

        $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>';            
    

    You are not contactinaging the PHP variable correctly.

    can't be used in any eco/print statements. Infact it itself is a PHP code and should only be used separately.

    Ex - in a new php page you can do this

    <select>
    <option value="0">Choose</option>
    <?=$options?> 
    Suggested way is
    <?php echo $options; ?>
    </select>
    
    点赞 评论
  • dongnvwang8591 2014-10-14 10:00

    Have you checked for session that if session is setted or not! If setted then make sure that your session id matches your table column.

    点赞 评论
  • duanjiao3686 2014-10-14 10:18
        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> 
    
    点赞 评论

相关推荐 更多相似问题