In my form I have a select input field that is populated with data from mysql db. I am trying to display the selected value in this select input field from table academy where status is either active or inactive. In the example below the academy has a status of inactive but when trying to echo the selected value it displays incorrectly; active instead of inactive. Here is an 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>
Stored Values in academy table:
+------------+-------------------+----------+
| academy_id | name | status |
+------------+-------------------+----------+
| 15 | Brown High School | Inactive |
+------------+-------------------+----------+
var_dump($status, $option);on each foreach iteration and see what's wrong - u_mulder