<?php
$sql = "SELECT id, name FROM cities";
$stmt = $DBcon->prepare($sql);
$stmt->execute();
$cities = $stmt->fetchAll();
$current_city_id = '';
$current_city_id=$cities[0]['id'];
$dropdown = '<select name="city">';
foreach ($cities as $city) {
$selected='';
if ($current_city_id==$city['id']) $selected=" selected";
$dropdown .= '<option value="'.$city['id'].'">' . $city['name'] .'</option>';
}
$dropdown .='</select>';
echo $dropdown;
?>
选择的值未显示在下拉菜单中,然后用户按下更新按钮。无法找到问题所在。
答案 0 :(得分:2)
您没有在选项...
中添加 $ selected 值<?php
$sql = "SELECT id, name FROM cities";
$stmt = $DBcon->prepare($sql);
$stmt->execute();
$cities = $stmt->fetchAll();
$current_city_id = '';
$current_city_id=$cities[0]['id'];
$dropdown = '<select name="city">';
foreach ($cities as $city) {
$selected='';
if ($current_city_id==$city['id']) $selected=" selected";
$dropdown .= '<option value="'.$city['id'].'" '.$selected.'>' . $city['name'] .'</option>'; //Change Here
}
$dropdown .='</select>';
echo $dropdown;
?>
答案 1 :(得分:1)
您不打印$ selected变量。 $ selected变量应打印在选项
中 <?php
$sql = "SELECT id, name FROM cities";
$stmt = $DBcon->prepare($sql);
$stmt->execute();
$cities = $stmt->fetchAll();
$current_city_id = '';
$current_city_id=$cities[0]['id'];
$dropdown = '<select name="city">';
foreach ($cities as $city) {
$selected='';
if ($current_city_id==$city['id']) $selected=" selected";
//print out selected variable
$dropdown .= '<option '.$selected.' value="'.$city['id'].'">' . $city['name'] .'</option>';
}
$dropdown .='</select>';
echo $dropdown;
?>