I have an form with an multiple select in the while loop:
while ($row_i = mysql_fetch_array($res_i))
{
$i++;
// maak select name
$name_bewerking_id = 'bewerking_id'.$i;
?>
<tr valign="top">
<td>
<select name="<?php echo $name_bewerking_id ?>[]" multiple="multiple" size="2">
<?php
$sql = "SELECT id, bewerking FROM bewerkingen ORDER BY bewerking ASC";
$res = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($res))
{ ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['bewerking']; ?></option>
<?php } ?>
</select>
</td>
</tr>
<?php
}
When the form is send:
$bewerking_id[$i] = array();
$bewerking_id[$i] = $_POST['name_bewerking_id'][$i];
if(isset($bewerking_id_temp[$i]))
{
foreach($bewerking_id_temp[$i] as $temp[$i])
{
array_push($bewerking_id[$i], $temp[$i]);
}
}
Returning to the form:
for ($i = 0; $i <= $aantal_regels_corr; $i++)
{
// maak select name
$name_bewerking_id = 'bewerking_id'.$i;
?>
<tr valign="top">
<td>
<select name="<?php echo $name_bewerking_id ?>[]" multiple="multiple" size="2">
<?php
$sql = "SELECT id, bewerking FROM bewerkingen ORDER BY bewerking ASC";
$res = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($res))
{ ?>
<option <?php if(isset($bewerking_id[$i]) && in_array($row['id'], $bewerking_id[$i])){ echo 'selected="selected"'; } ?> value="<?php echo $row['id']; ?>"><?php echo $row['bewerking']; ?></option>
<?php } ?>
</select>
</td>
</tr>
<?php
}
When returning to the form (when one of the other fields is not filled in) the chosen option(s) are lost and not selected again.
Where did I messed up?
You read POST data with this identifier 'name_bewerking_id'
but the select name is given by <?php echo $name_bewerking_id ?>
with $name_bewerking_id = 'bewerking_id'.$i
If assuming you are passing the form information between 3 different pages, you will need to use $_SESSION variables for that. Normal PHP variables cannot be passed between pages, only $_SESSION variables.
For example:
Page 1
<form ...>
<input name="text1" type="text" />
<input type="submit" />
</form>
Page 2
// must start the session before session variables can be used
start_session();
$inputTextBox1 = $_SESSION["textBox1"] = $_POST["text1"];
Page 3
<?php start_session(); ?>
<html>
...
<form ...>
<select>
<?php while ... { ?>
<option <?php if(!empty($_SESSION["textBox1"])) { echo "selected=\"selected\""; } ?>>Some Text</option>
<?php } // End while ?>
</select>
</form>
...
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.