PHP - making a switch statement using id from form input

17,269

Solution 1

switch($_POST['answer']) {

case 'Yes':
   // do soemthing
   break;
case 'No':
   // do something
   break;
}

Solution 2

There are many errors to this. Please study the following:

echo '<form method ="post" action="Creatures.php">
<button name="answer" type="submit" value="Yes">Yes</button>
<button name="answer" type="submit" value="No">No</button>
</form>';

switch($_POST['answer'])
{
   case 'Yes':
        echo "It's a goldfish";
        break;
   case 'No':
        echo "It's a eel";
        break;
}

Also see this and this.

Share:
17,269
Harry12345
Author by

Harry12345

Updated on June 04, 2022

Comments

  • Harry12345
    Harry12345 almost 2 years

    I'm making a short quiz in PHP that tells you what creature your thinking of based on 4 yes/no questions. I have made it so that depending on your answer to each question you get taken to a different question, I did this using mainly switch statements.

    My question is is there any way that I can make a switch statement with the condition as the id from the submit buttons from the form?

          echo "<form method ='post' action='Creatures.php'>
         <input type='submit' name='answer' id='1' value='Yes' />
         <input type='submit' name='answer' id='2' value='No' />
         </form>";
    

    This is the form I'm using to display the buttons, I have made it so that each button has a different id so at the end of the quiz, depending on what the id of the last button pressed is, I can display the right answer. Below is what I tried to do but it didn't work.

    switch($_POST['id'])
    {
     case 1: echo "It's a goldfish";
     case 2: echo "It's a eel";
    }
    

    Also these fields are the only ones which use id's throughout the whole web page, any suggestions on how I can get this to work properly, not necessarily using switch statements?

  • tigrang
    tigrang almost 12 years
    and switch 'Yes' and 'No' - see my comment
  • Waqar Alamgir
    Waqar Alamgir almost 12 years
    as you have same name='answer' they can not be of 2 at the same time unless you define them as array like name='answer[]'
  • tigrang
    tigrang almost 12 years
    But only 1 is ever being posted. They are submit buttons.
  • Harry12345
    Harry12345 almost 12 years
    I have done everything you said and have added a hidden input field, so it is now working, yaayyy!