ds42774 2014-04-22 07:43
浏览 40

重新加载同一页面时使用php设置选择选项

I have a php select populated and given a matching value by using php to loop through the results of a sql query.

$result = mysqli_query($con, "select * from course")

echo "<form action='' method='post'>";
echo "<select name='CourseSelect'>";
echo "<option value='0'> - Select Course - </option>";
while($row = mysqli_fetch_array($result))
{
 echo "<option value='" . $row['Title'] ." '>" . $row['Title'] . "</option>";
}

echo "</select>";
echo "<input name='SubmitCourse' type='submit'>";
echo "</form>";

That gives me a drop down list populated with all course titles, upon submission I can access the selected value using $_POST['CourseSelect'];

However the drop down (select) resets itself to the default value when the page reloads.

How can I keep that option selected using php?

I know that I can use the selected keyword inside of an a select option to make that option the default selected option.

for example the second option would be selected when loading the page:

<select>
<option>One</option>
<option selected>Two</option>
<option>Three</option>
</select>
  • 写回答

5条回答 默认 最新

  • dourui7186 2014-04-22 07:48
    关注

    You can make it simple as

    while($row = mysqli_fetch_array($result))
    {
     $select = '';
     if( isset($_POST['CourseSelect']) && $_POST['CourseSelect'] == $row['Title'] ) $select = 'SELECTED';
     echo "<option value='".$row['Title']."' ".$select.">" . $row['Title'] . "</option>";
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看