在我的表单中,我有一个select字段,其中填充了来自mysql db的数据。我目前无法显示此选择字段的选定值。数据来自名为academy
的表格,每个学院都有status
active
和inactive
。表中的status字段是枚举类型。我试图通过选择输入显示存储在表中的值作为选定的选项。这是一个EXAMPLE。
//Database connection
<form action="" method="post">
try {
$db_con = new PDO($dsn, $user, $password);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$db_select1 = $db_con->prepare("
SELECT a.name,
a.academy_id
FROM academy a
WHERE a.academy_id = 15
");
if (!$db_select1) return false;
if (!$db_select1->execute()) return false;
$results1 = $db_select1->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results1)) return false;
foreach ($results1 as $value1){
$result1 .= "<strong>Academy Name: </strong>".$value1['name']."</br>";
$result1 .= "<strong>Academy ID: </strong>".$value1['academy_id']."</br>";
}
echo $result1;
?>
<strong>Academy Status:</strong>
<?php
//Populate select input
$table_name2 = "academy";
$column_name2 = "status";
echo "<select name=\"$column_name2\"><option>Select one</option>";
$sql1 = 'SHOW COLUMNS FROM '.$table_name2.' WHERE field="'.$column_name2.'"';
$row1 = $db_con->query($sql1)->fetch(PDO::FETCH_ASSOC);
foreach(explode("','",substr($row1['Type'],6,-2)) as $option) {
echo "<option value='$option'>$option</option>";
}
echo "</select></br>";
?>
<input type="submit" name="submit" value="Update">
</form>
将值存储在academy
表中:
+------------+-------------------+--------+
| academy_id | name | status |
+------------+-------------------+--------+
| 15 | Brown High School | Active |
+------------+-------------------+--------+
答案 0 :(得分:1)
您需要使用select html标记的“selected”属性:
http://www.w3schools.com/tags/att_option_selected.asp
在动态填充选项时执行此操作:
$selected = '';
foreach(explode("','",substr($row1['Type'],6,-2)) as $option) {
if ($status == $option) // $status is the status of your record from the database
$selected = "selected";
echo "<option value='$option'" . $selected. ">$option</option>";
}
除了名称和学院ID
之外,您还需要更改sql语句以选择状态SELECT a.name,
a.academy_id
a.status
FROM academy a
WHERE a.academy_id = 15
然后显然填充$ status变量:
$status = $value1["status"];
答案 1 :(得分:0)
foreach(explode("', '", substr($row1['Type'], 6, -2)) AS $option) {
$selected='';
if($selected == $selected_value) $selected=" selected='selected'";
echo "<option value='".$option."'".$selected.">".$option."</option>";
}