0

I'm practicing with PHP and tried to design a simple program. If the user types "red" or "blue" into the textfield and hits "submit", the program is supposed to print "Your favorite color is red" or "Your favorite color is blue." But for some reason it doesn't work.

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <?php
     $favcolor = $_GET["favcolor"];

    switch($favcolor){
        case "red":
            echo "Your favorite color is red!";
            break;
        case "blue":
            echo "Your favorite color is blue!";

    }
    ?>
     <form action = "index.php" method = "post">
        <input type ="text" name="favcolor">
        <input type ="submit" name="submit">
    </form>

</body>

However, I get this error "Notice: Undefined index: favcolor in C:\xampp\htdocs\Fav_Colors\index.php on line 14"

What's the deal?

  • 3
    Why would you set the form to post and then check `$_GET`??? Use `$_POST["favcolor"]` – AbraCadaver Jun 12 '17 at 18:55
  • Oh, my error. I was just getting desperate and was changing things around. But even when they are both "POST" or both "GET" its the same error. – Dennis Markham Jun 12 '17 at 19:00
  • @AbraCadaver - Your point is correct, but, you missed the fact, that PHP will be executed independent of the submit button click and hence, the error will continue since, Favcolor is not set in the beginning. Either write the PHP code in a separate file or, enable the PHP code only when the onclick event on submit is triggered. Alternatively use a isset call to check if variable favcolor is set and then display the line. – Umashankar Das Jun 12 '17 at 19:04
  • @UmashankarDas: No I didn't miss that, the duplicate addresses that but not the diff between post and get. – AbraCadaver Jun 12 '17 at 19:08
  • Okay, so I got rid of the error using "$fcoutput = "";" followed by "$fcoutput = isset($_POST["fcinput"]);" but now it always say "your favorite color is red" no matter what :/ – Dennis Markham Jun 12 '17 at 19:11
  • @AbraCadaver If you check Dennis 's comment, he is still getting the error even after a change from POST to GET – Umashankar Das Jun 12 '17 at 19:12
  • @UmashankarDas: No shit, the DUPLICATE answers the question. – AbraCadaver Jun 12 '17 at 19:13
  • Nevermind, I figured it out. How do you close these questions? – Dennis Markham Jun 12 '17 at 19:23

0 Answers0