Solved

How to retain dropdown selection when posting form back to self

Posted on 2011-03-09
11
504 Views
Last Modified: 2012-05-11
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>
0
Comment
Question by:TrevorParnhamntl
  • 4
  • 3
  • 3
  • +1
11 Comments
 
LVL 13

Expert Comment

by:devlab2012
ID: 35085182
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
 
LVL 13

Expert Comment

by:devlab2012
ID: 35085210
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
 
LVL 1

Author Comment

by:TrevorParnhamntl
ID: 35085264
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
 
LVL 13

Expert Comment

by:devlab2012
ID: 35085889
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
 
LVL 16

Expert Comment

by:Chris Harte
ID: 35095687
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:TrevorParnhamntl
ID: 35096202
Munterman.
Can you elaborate on this, please?

0
 
LVL 16

Expert Comment

by:Chris Harte
ID: 35096834
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
 
LVL 1

Author Comment

by:TrevorParnhamntl
ID: 35112243
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
 

Expert Comment

by:etanox
ID: 35113369
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
 
LVL 16

Accepted Solution

by:
Chris Harte earned 500 total points
ID: 35127438
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
 
LVL 1

Author Closing Comment

by:TrevorParnhamntl
ID: 35132815
Wonderful Munterman.
That works. I was getting very close but couldn't find the right combination. Thank you for your perseverence
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now