Excersie from freeCodeCamp gives different result

Im studying php from freeCodeCamp’s youtube video.

The exercise at the video’s timestamp gives me this when compiled:
Notice: Undefined index: name in C:\wamp64\www\zadaci\form\site.php on line 13
(Line 13 = <?php echo $_GET["name"] ?>)
What did I do wrong?

site.php:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <form action="site.php" method="get">
            Name: <input type="text" name="name">
            <input type="submit">
        </form>
        <br>
        <?php echo $_GET["name"] ?>
    </body>
</html>

Hello, I’m no master but I know this one. I’ts not defined yet, input name or some text and u wont get the error and it will work ok.

The proper handling of input data is -

  1. Detect the input. For a single $_GET variable, you would typically use isset().
  2. Trim the input.
  3. Validate the input. If the input is ‘required’, and it’s not valid, that’s an error. You would setup and display an error message for the visitor, and not attempt to use the input. If the input is not required, it didn’t pass the validation, and it has an acceptable default value, you would set it to the default value.

BTW - to get a form to submit to the same page it is on, you can leave the entire action="…" attribute out of the form tag. Also, the default method is get, so you can leave the entire method=“get” attribute out too.

I did this and it worked, is this ok? Tried with GET but apparently that doesn’t work

<?php
$username = "";
?>
<html>
    <body>
        <form method="post">
            Name: <input type="text" name="username"><br>
            <input type="submit">
        </form>
        <br>
        <?php
        if($_SERVER["REQUEST_METHOD"] == "POST")
            echo $_POST["username"];
        ?>
    </body>
</html>

EDIT: I don’t know how to get it work with GET. I tried 3 Form exercises from 3 different sources and all of them give me the notice/error using GET. Any good sources you can recommend is appreciated

If you are using a post method form, testing the server request method is the best way of detecting when there is post data. However, if this is the case, the post method form processing code should be located above the start of the html document since its purpose is to perform an action on the server, such as inserting, deleting, or updating data in a database, sending an email, uploading a file…

You would need to post your attempt at the get method form processing code to get help with what was wrong with it.

Sponsor our Newsletter | Privacy Policy | Terms of Service