Hopeless Coder 99
Hopeless Coder 99

Reputation: 5

HTML dropdown and text form, php if statement?

essentially I have a database with a list of people & their ages. I would like to be able to read these, and I have set up a dropdown with either Name, and age as the attributes, then I have a text box where the user inputs either the name or age based on the choice in the dropdown.

<form target="_blank" action="results.php" method="post">
  <select name="attr">
    <option value="name">Name</option>
    <option value="age"> Age </option>
  </select>
<input type="text" id="name" name="name">
<input type="submit" name="submit" value="View Results">
</form>

Then in my results.php file I have if statements if(array_key_exists('name', $_POST)) or with age and then I am able to retrieve a table correctly. However, the above code is only working for name and not age, due to the 3rd last line. I basically want to set up an if statement here, if the selection in the dropdown is name or age, the text field to be name or age and retrieve it (which works correctly in my results.php). I have tried a switch statement and if/else to no avail. Any help would be appreciated!

Upvotes: 0

Views: 224

Answers (1)

Ivan Ponomarev
Ivan Ponomarev

Reputation: 46

In your case you have only "attr", "name" and "submit" in your POST array. What is used in the "option" tags - are values. Depends on what is chosen by user - it will be put to $_POST['attr']

So if person will choose "Name" value in dropdown box - then in $_POST['attr'] will be contained value "name". This value isn't related with the $_POST['name']. $_POST['name'] is taken from your input text field (tag).

So name attribute of the tag - is the key of the $_POST or $_GET arrays. But Values of them are based on the logic of the field.

Upvotes: 1

Related Questions