Avatar of TrevorParnhamntl
TrevorParnhamntl
 asked on

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>
PHP

Avatar of undefined
Last Comment
TrevorParnhamntl

8/22/2022 - Mon
devlab2012

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>\
devlab2012

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";
}
TrevorParnhamntl

ASKER
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>
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
devlab2012

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.
Chris Harte

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
TrevorParnhamntl

ASKER
Munterman.
Can you elaborate on this, please?

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Chris Harte

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.
TrevorParnhamntl

ASKER
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.
etanox

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
Your help has saved me hundreds of hours of internet surfing.
fblack61
ASKER CERTIFIED SOLUTION
Chris Harte

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
TrevorParnhamntl

ASKER
Wonderful Munterman.
That works. I was getting very close but couldn't find the right combination. Thank you for your perseverence