I have a very simply form with multiple text boxes and a couple of drop downs. I am populating the drop downs from MySQL with the following code which works fine (I'm just showing the code for the drop down to keep things simple):
<?php
$hostname_sql = "localhost";
$database_sql = "database";
$username_sql = "user";
$password_sql = "password";
$sql = mysql_pconnect($hostname_sql, $username_sql, $password_sql) or trigger_error(mysql_error(),E_USER_ERROR);
$query_Recordset1 = "SELECT id, username FROM database ORDER BY username ASC";
$Recordset1 = mysql_query($query_Recordset1, $sql) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
<html>
<head>
<title></title>
</head>
<body>
<form id="form1" name="form1" method="post" action="test.php">
<label>
<select name="form" id="form">
<?php
do {
?>
<option value="<?php echo $row_Recordset1['id']?>"><?php echo $row_Recordset1['username']?></option>
<?php
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
$rows = mysql_num_rows($Recordset1);
if($rows > 0) {
mysql_data_seek($Recordset1, 0);
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
}
?>
</select>
</label>
<p>
<label>
<input type="submit" name="button" id="button" value="Submit" />
</label>
</p>
</form>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>
My question is... how can I get the drop down menu to retain the information selected by the user if form validation fails (for example he / she forgets to fill out a required text field) and so he / she is returned to the form with an error message.
With a static form, each option would be coded as follows:
<option value="Albania"<?php if ($_POST['location_currency'] == "Albania") echo " selected"; ?>>Albania</option>
I've tried combining it with the dynamic option value:
<option value="<?php echo $row_Recordset1['id']?>"><?php echo $row_Recordset1['username']?></option>
To produce:
<option value="<?php echo $row_Recordset1['id']?>"<?php if ($_POST['form1'] == "echo $row_Recordset1['id']") echo " selected"; ?>><?php echo $row_Recordset1['username']?></option>
without success. I just get a blank page. Tried escaping double quotes, that didn't work either.