Can't get radio values ​​in php

Ok, this is kind of a nob question, but I've searched and searched and can't figure out how to do this. I cannot get the values ​​of my radio buttons using php.

<!DOCTYPE html>
<html>
    <body>
        <form action="" method="POST">
            Do you buy your lunch?
            <br>
            <input type="radio" name="doyoubuy" value="Yes" checked>Yes
            <br>
            <input type="radio" name="doyoubuy" value="No">No
            <br><br>
            <input type="submit" value="submit">
        </form>
        <?php
            if (isset($_POST['submit'])) {
                if (isset($_POST['doyoubuy'])) {
                    echo "You have selected :".$_POST['doyoubuy'];
                }
            }
        ?>
    </body>
</html>

      

Thank!!!

+3


source to share


3 answers


You check if (isset($_POST['submit'])) {

But your submit button is not actually named ...

So just call it:



<input type="submit" value="submit" name="submit">

Then your code for radio stations should work fine.

+5


source


The action must be the current page. In your case, it is ""



0


source


I offer this HTML and PHP for your consideration:

<html>
    <body>
        <form method="POST">
            Do you buy your lunch?
            <br>
            <input type="radio" name="doyoubuy" value="Yes" checked>Yes
            <br>
            <input type="radio" name="doyoubuy" value="No">No
            <br><br>
            <input type="submit" name="submit" value="submit">
        </form>

        <?php
        if (isset($_POST) && $_POST != NULL) {
          if ( $_POST['doyoubuy']  == 'Yes' || $_POST['doyoubuy'] == 'No') {
             $answer = $_POST['doyoubuy'];
             echo "You selected :". $answer;
          }
        }
        ?>

    </body>
</html>

      

What to check if the form has been submitted. If so, assuming each field has a name on the form, then some value will be associated with each field, which removes the need to validate if the submit button is set. In addition, if the user submitted the form, but forgot to fill in, for example, a text input, then this field value will still be set; it will be set to an empty string.

It is inappropriate to trust the posted value of the form and consider it safe to use. In this case, I check that the answer is what I expect, just in case someone can spoof the form and change the answer to something else than I thought.

By default, if you ignore the form's ACTION attribute, its value is the URL of the page containing the form.

0


source







All Articles