• PHP Help PHP Coding
  • Drop down menu populated from MySQL that retains information if validation fails

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.

    Your value is different than your innerHTML right.

    Here's how I like to handle this whole situation that I think you'll appreciate and like:

    $html = '<select name"select">';
    foreach($dbOptions as $option)
    {
    	$htmlSel = NULL;
    	if($option == $_REQUEST['select'])  $htmlSel = ' selected="selected"'; // NOTE: $_REQUEST catches both $_POST and $_GET passed variables
    	$html .='<option value="' .$option. '"' .$htmlSel. '>' .stripslashes($option). '</option>';
    }
    $html .= '</select>';
    

    It's not tailored to your situation, but looking at your code, you'll be able to retro-fit just fine.

      This is such a common need with PHP forms that you really should consider using a function or class for this. More code but re-usable. Consider the following

      	/**
      	 * selectMenu: auto generates a "select-one" or combo box form control
      	 * with an optional default input. Options are input in fhe form of an associative array
      	 * where the key is the label of the option and the value is the value attribute of
      	 * the option. Attributes are input in the form of an associative array
      	 * ie. 'class'=>'dropdown'. If set to "multiple" with attributes, $input can be an array of choices
      	 *
      	 * @param string $name
      	 * @param array $op
      	 * @param mixed $input
      	 * @param array $attributes
      	 * @return string
      	 */
      	function selectMenu($name,$op,$input='',$attributes=null)
      	{
      		if(!empty($name))
      		{
      
      		$attr = $attributes;
      		if(is_array($attributes))
      		{
      			$attr = '';
      			foreach($attributes as $key=>$aValue)
      			{
      				$attr .= " $key=\"$aValue\"";
      			}
      		}
      		$multivalue = false;
      		if(is_array($input) && isset($attributes['multiple']))
      		{
      			$multivalue = true;
      		}
      		$tag = "<select name=\"$name\"$attr>\n[options]</select>\n";
      		$options = '';
      		foreach($op as $key=>$value)
      		{
      			$selected = '';
      			if(is_numeric($key))
      			{
      				$key = $value;
      			}
      			if($multivalue)
      			{
      				if(in_array($value,$input))
      				{
      					$selected = ' selected="selected"';
      				}
      			}
      			else
      			{
      				if($value == $input)
      				{
      					$selected = ' selected="selected"';
      				}
      			}
      			$options[] = "<option value=\"$value\"$selected>$key</option>";
      		}
      		if(!empty($options))
      		{
      			$tag = str_replace('[options]',"\t".implode("\n\t",$options)."\n",$tag);
      		}
      		else
      		{
      			$tag = str_replace('[options]',"\n",$tag);
      		}
      		return $tag;
      	}
      	else
      	{
      		return '';
      	}
      }
      
      // use
      $op = array('Steak'=>1,'Chicken'=>2,'Fish'=>3);
      // $input can come from anywhere including database or $_GET or $_POST
      $input = 2;
      // attributes
      $attributes = array('class'=>'dropdown');
      $menu = selectMenu('mealchoice',$op,$input,$attributes);
      echo($menu);
      
        Write a Reply...