Beginner php "Warning: Undefined array key"

lavendercake

So, I'm learning PHP and I keep getting "Warning: Undefined array key" in $GET_["fname"] and $GET_["age"]:

<main>

    <form action="inputs.php" method="get">
        Name: 
        <br/>
        <input type="text" name="fname">
        <br/>
        Age:
        <br/>
        <input type="number" name="age">
        <br/>
        <input type="submit" name="submit">

    </form>
        <br/>
        Your name is <?php echo $_GET["fname"]; ?>
        <br/>
        Your age is <?php echo $_GET["age"]; ?>

</main>
Joshua Angnoe

I'll assume you want to know how to get rid of this error message.

The first time you load this page you display a form and $_GET is empty (that's why it is triggering warnings). Then you submit the form and the fname and age parameters will be added to the url (because your form's method is 'get').

To resolve your issue you could wrap the two lines inside some if-statement, for example:

<?php if(isset($_GET['fname']) && isset($_GET['age'])): ?>
        <br/>
        Your name is <?php echo $_GET["fname"]; ?>
        <br/>
        Your age is <?php echo $_GET["age"]; ?>
<?php endif; ?>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related