【问题标题】:Display value from mysql table as 'selected' in a select input field在选择输入字段中将 mysql 表中的值显示为“已选择”
【发布时间】:2013-12-01 07:17:35
【问题描述】:

在我的表单中,我有一个选择输入字段,其中填充了来自 mysql db 的数据。我正在尝试从表academy 中显示此选择输入字段中的选定值,其中statusactiveinactive。在下面的示例中,学院的状态为inactive,但在尝试回显所选值时,它显示不正确; active 而不是 inactive。这是EXAMPLE

<form action="" method="post">
//Read results from database
$db_select1  = $db_con->prepare("
SELECT a.name, 
       a.academy_id,
       a.status
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>";
          $status = $value1["status"]; 
    }

    echo $result1;


echo $resutl1;
?>
 <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);
                $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>";
                }
                echo "</select></br>";   
        ?>
 <input type="submit" name="submit" value="Update">
 </form> 

学院表中的存储值:

+------------+-------------------+----------+
| academy_id |       name        | status   |
+------------+-------------------+----------+
|       15   | Brown High School | Inactive |
+------------+-------------------+----------+

【问题讨论】:

  • var_dump($status, $option); 在每次 foreach 迭代中,看看有什么问题

标签: php


【解决方案1】:

试试SELECTED=SELECTED

foreach(explode("','",substr($row1['Type'],6,-2)) as $option) {
if ($status == $option){
      $selected = "selected=selected";

}else{

      $selected=''
}

      echo "<option value='$option'" . $selected. ">$option</option>";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2021-12-29
    • 2021-02-19
    • 2023-01-27
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多