Solved

How to retain dropdown selection when posting form back to self

Posted on 2011-03-09
11
503 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 1

Author Comment

by:TrevorParnhamntl
Comment Utility
Munterman.
Can you elaborate on this, please?

0
 
LVL 16

Expert Comment

by:Chris Harte
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Wonderful Munterman.
That works. I was getting very close but couldn't find the right combination. Thank you for your perseverence
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
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 dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

771 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

12 Experts available now in Live!

Get 1:1 Help Now