Solved

How to retain dropdown selection when posting form back to self

Posted on 2011-03-09
11
505 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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 17

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
 
LVL 1

Author Comment

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

0
 
LVL 17

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 17

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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

778 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