Echos showing before input is received

965 views php
-1

I am new at PHP. Basically, I'm trying to make a simple if else statement that will let someone know if they are too young to see a rated R movie. The problem that I'm having is that what I want to output is shown way before I even get the input (age).

enter image description here

This is my current code:

<form action="movieProgram.php" method="post">
How old are you? <input type="text" name="age"/>
<input type="submit">
</form>



<?php 

/*if ($age < 17){ 
The $_POST['age'] retrieves data from the
form that is named age

*/
$age = $_POST["age"];
if ($age == ""){
    echo "";
}
elseif ($age < 17){
    echo "You are too young to watch the movie.";
}
else {
    echo "You are old enough to watch the movie.";
}
 ?>

How would I fix it? Any suggestions?

answered question

You can put a name attribute to your submit button then check if the form is submitted or not.

Your problem is when you first access the page $_POST is empty so $age will be NULL which will fail both your comparisons; hence your code outputs "You are old enough to watch the movie". You need to change the assignment of $age to stop that happening by checking that $_POST['age'] is set before trying to use it e.g. $age = isset($_POST['age']) ? $_POST['age'] : ""; or if you're using PHP7 $age = $_POST['age'] ?? "";

1 Answer

9

You can put a name attribute to your submit button then check if the form is submitted or not. Here is a demo what i have talked about

<form action="#" method="post">
How old are you? <input type="text" name="age"/>
<input type="submit" name="submit">
</form>



<?php 

/*if ($age < 17){ 
The $_POST['age'] retrieves data from the
form that is named age

*/
if(isset($_POST['submit'])) {
    $age = (int)$_POST["age"];
    if ($age == ""){
        echo "";
    }
    elseif ($age < 17){
        echo "You are too young to watch the movie.";
    }
    else {
        echo "You are old enough to watch the movie.";
    }
}

 ?>

posted this

Have an answer?

JD

Please login first before posting an answer.