how do retain value of dropdown box in php

2019-08-16 08:58发布

问题:

I will try to make it simple as possible. I know how to select a default value in dropdown. My problem is how to make the last option in the dropdown as default "interactively" for next time. so that means that I cannot hardcode the default value.

Lets say I want to multiply 2 numbers. I have two drop down boxes and contain number 1 to 10; at the very first time it will say 1 and 1 since if no default is mentioned, then the default is the number at 1st position. Lets say if somebody picks 2 in the 1st and 6 in the second. Once the user hits calculate, the page will refresh, the answer 12 will be displayed. I still want 2 and 6 stil to be there, and NOT go back to 1 and 1

Please note that if I have action set to "answer.php", and display the answer on a new page and have a back button to come back to initial page. There is no problem. but I don't want that. I want to stay on the same page.

I am not using mysql. All have is a simple for loop and I dynamically load values 1 to 10

I believe I need something like selected = ?????? please fill the blank and where would I put this in the for loop

I have spent whole day on this on google but no luck to what I want

Thanks

Amit

回答1:

As I see it, there are several ways to do this:

  1. On the page that receives the form data, check which option the user selected and store it in a cookie. When you generate your form, check if this cookie is present; if so, use its data as the default value. This is probably the simplest option.
  2. Store the selected option in a PHP session variable. This will work the same way as #1, except default values will not be saved if the user closes his browser.
  3. Use a login system and store the default value in a database.


回答2:

There are many ways to do this, the differences come down to how 'deep' you want the storage to be. Without wasting too much time here is a quick list of storage options:

  • POST vars (this is the solution that best suits your scenario)
  • Cookies
  • Session
  • Database
  • Server Filesystem
  • etc etc

Basically the simplest technique is to take the data that is passed and redisplay it, so for your form you have 2 inputs, leftval & rightval, the user hits submit on the form and you multiply them to show the result.

When you build the page to show the result use the $_POST['leftval'] & $_POST['rigtval'] to populate them on the new page. Make sure to sanitize the values and escape them on the way out!