How to retain dropdown selection when posting form back to self

Hello,
I have a form which has a dropdown list which is populated from a mysql database. It contains a lot of items (over 200). I then want the user to select from the drop down list, add some further user input, do a calculation using that input and post the answer back to the page, together with retaining the selection from the dropdown list. The population of the dropdown, the selection of an item from it and the calculation are all triggered from the same form submit
Everything is working fine except I cannot retain the selection in the dropdown list. I can retrieve the value from $_Post, but how does this become the selection in the dropdown? At the moment It copies it to the page and the dropdown displays the first item in the list. Here is my code and any help would be gratefully received

<?php
ini_set('display_errors','1');
error_reporting(E_ALL);
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="calc.css" />

</head>
<body>
<div align=center><h1><b>Wrington Online World </b></h1></div>
<ul id="list-nav">
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">Prices</a></li>
<li><a href="#">Contact</a></li>
</ul>
<HR size="3" color="6495ed">
<?php
/* declare some relevant variables */
$DBhost = "localhost";
$DBuser = "root";
$DBpass = "xxxxxxxxxx";
$DBName = "mail_management";
$table  = "Country_data";

mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database");
mysql_select_db($DBName) or die("Unable to select database $DBName");

$sql = "SELECT * FROM $table ";
$res = mysql_query($sql);

$num = mysql_num_rows($res);
mysql_close();
?>


<div align=center><h2><b>Rate Calculator</b></h2></div>
      <FORM method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php            
echo "<select name='country_name'>\n";

while ($data = mysql_fetch_array($res, MYSQL_ASSOC))
{
echo " <option value='{$data['country_name']}'>{$data['country_name']}</option>\n";
}

echo "</select>\n";
?>
            Weight(kgs):<input name="weight" type="text" >
              Length(cms):<input name="length" type="text" >
               Width(cms):<input name="width" type="text" >
             Depth;(cms)<input name="depth" type="text" >

<input type="submit" name="submit" value="Calculate">            
</form>

<?php
if(isset($_POST['submit']))
{
echo $_POST['country_name'];


$weight=$_POST['weight'];    
$length = $_POST['length'] ;
$width = $_POST['width'] ;
$depth = $_POST['depth'] ;
$a= '('.$length.'*'.$width.'*'.$depth.')/5000';
$c = ($length * $width * $depth)/5000;
eval("\$b = $a;");
?>
<h3> <?php echo "Volumetric weight is $b"; ?></h3>  
<?php
   
}
?>

</body>
</html>
LVL 1
TrevorParnhamntlAsked:
Who is Participating?
 
Chris HarteConnect With a Mentor ThaumaturgeCommented:
I think this is what you are looking for.

while ($data = mysql_fetch_array($res, MYSQL_ASSOC))
{
    if ($_POST['country_name'] == $data['country_name'])
    {
        echo " <option value='{$data['country_name']}' selected>{$data['country_name']}</option>\n";        
    }
    else
    {
        echo " <option value='{$data['country_name']}'>{$data['country_name']}</option>\n";
    }
}
0
 
devlab2012Commented:
Using $_POST, store the value of drop-down selection is a variable. In the following line, compare this value with $data['country_name'] using IF statement. If it is true the echo the word "selected"

<option value='{$data['country_name']}'>{$data['country_name']}</option>\
0
 
devlab2012Commented:
Here is complete code:

while ($data = mysql_fetch_array($res, MYSQL_ASSOC))
{
if ($data['country_name'] == $_POST['country_name'])
  echo " <option value='{$data['country_name']}' 'selected'>{$data['country_name']}</option>\n";
else
  echo " <option value='{$data['country_name']}'>{$data['country_name']}</option>\n";
}
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
TrevorParnhamntlAuthor Commented:
I've tried that previously and I've just tried it again, but it doesn't work.
The complete form code is now as below, but still get the same result

      <FORM method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php            
echo "<select name='country_name'>\n";

while ($data = mysql_fetch_array($res, MYSQL_ASSOC))
{
if ($data['country_name'] == $_POST['country_name'])
  echo " <option value='{$data['country_name']}' 'selected'>{$data['country_name']}</option>\n";
else
  echo " <option value='{$data['country_name']}'>{$data['country_name']}</option>\n";
}

echo "</select>\n";
?>
            Weight(kgs):<input name="weight" type="text" >
              Length(cms):<input name="length" type="text" >
               Width(cms):<input name="width" type="text" >
             Depth;(cms)<input name="depth" type="text" >

<input type="submit" name="submit" value="Calculate">            
</form>
0
 
devlab2012Commented:
I am not much familiar with PHP, what is the meaning of {$data['country_name']}? Will it add the braces {} with the country name coming from database? If this is the case then you have to change the IF statement accordingly.
0
 
Chris HarteThaumaturgeCommented:
The post variables are reloading from the database every time you reload the page. Use sessions and $_SESSION[] variables instead

http://uk2.php.net/manual/en/intro.session.php
0
 
TrevorParnhamntlAuthor Commented:
Munterman.
Can you elaborate on this, please?

0
 
Chris HarteThaumaturgeCommented:
If I read the question right, you want the user to select a value from a dropdown, submit the page and retain the value as the selected option on the dropdown menu. This means saving the selected value after a page submit. To save data in variables across page reloads you need to use sessions. Variables stored in $_SESSION[] are retained across reloads.
0
 
TrevorParnhamntlAuthor Commented:
Munterman,
Saving the data in variables is not the problem. I can do that with $_POST. What I need to know is how to then select the saved selection in the dropdown? The same thing happens if I use $_SESSION. I can select it if I add the index to a url, so I know it's possible. I just can't work out how. I've trawled the internet and so far all possible suggestions don't work.
0
 
etanoxCommented:
first I capture de post value in

$country_id="";
if (isset($_POST['country_id']) $country_id=$_POST['country_id'];

second
I have an array of the items of the menu (it may be in a session variable from the begining)

$arreglo[]=array('ID'->1,'NAME'->"COUNTRY 1");
$arreglo[]=array('ID'->2,'NAME'->"COUNTRY 2");
.....

last the menu is displayed:

echo "<select name=\"country_id\">";

if($country_id=="Country"){
            echo "<option value=\"Country\" selected>Country</option>";
      }else{
            echo "<option value=\"Country\">Country</option>";
      }
for($x=0;$x<count($arreglo);$x++){
      if($country_id==$arreglo[$x]['ID']){
                echo "<option value=\"".$arreglo[$x]['ID']."\" selected>".$arreglo[$x]['NAME'].</option>";
      }else{
                echo "<option value=\"".$arreglo[$x]['ID']."\">".$arreglo[$x]['NAME']."</option>";
      }
}

echo "</select>";

hope it is usefull
0
 
TrevorParnhamntlAuthor Commented:
Wonderful Munterman.
That works. I was getting very close but couldn't find the right combination. Thank you for your perseverence
0
All Courses

From novice to tech pro — start learning today.