<form action="" method="post">
<?php echo "<select id='date' name='date' class='input' >";
echo '<option value="">Please Select Date</option>'?>
<?php
$sql1 = "SELECT Distinct date,day
FROM errorlog order by date";
$result1=mysql_query($sql1,$con);
if (!$result1)
die ("Could not retrieve date" .mysql_error());
for ($counter = 0; $row = mysql_fetch_row ($result1); $counter++)
print ("<option value = '$row[0]'>$row[1] - $row[0]</option>");
echo "</select>";
?>
</form>
I need to save the selected value from the drop down menu even when submitting, means every time he selects a value form the drop down menu and click submit the value stays on the select
I would suggest getting the data for <select>
before outputting it, like that you can separate your SQL and output logic a little and keep things neater.
$sql1 = "SELECT Distinct date,day
FROM errorlog order by date";
$result1 = mysql_query($sql1,$con);
if (!$result1)
die ("Could not retrieve date" .mysql_error());
$data = array();
for ($counter = 0; $row = mysql_fetch_row ($result1); $counter++) {
$data[] = $row;
}
This will fetch the data and save it into $data
for now. One worry at a time. Then, if the user submits over POST, the value he submitted will be in $_POST['date']
. We can compare that value with one in $data
and use HTML's selected="selected"
attribute if a row in $data
matches it.
if (!empty($_POST['date'])) {
$user_date = $_POST['date'];
} else {
$user_date = '';
}
echo '<form ...>'; // etc.
echo '<select name="date">';
foreach ($data as $row) {
if ($row[0] == $user_date) {
echo "<option value = '$row[0]' selected='selected'>$row[1] - $row[0]</option>";
}
else {
echo "<option value = '$row[0]'>$row[1] - $row[0]</option>";
}
}
echo '</select>';
Note that this will issue multiple selected="selected"
outputs if the <select>
can have the same value multiple times.