Php 接收到输入前显示的回声

Php 接收到输入前显示的回声,php,if-statement,Php,If Statement,我是PHP新手。基本上,我试着做一个简单的if-else语句,让某人知道他们是否太年轻,不能看分级为R的电影。我遇到的问题是,我想要输出的东西在我得到输入(年龄)之前就已经显示出来了 这是我当前的代码: <form action="movieProgram.php" method="post"> How old are you? <input type="text" name="age"/> <input type="submit"> </form&g

我是PHP新手。基本上,我试着做一个简单的if-else语句,让某人知道他们是否太年轻,不能看分级为R的电影。我遇到的问题是,我想要输出的东西在我得到输入(年龄)之前就已经显示出来了

这是我当前的代码:

<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.";
}
 ?>

你多大了?

我该怎么修?有什么建议吗?

您可以在“提交”按钮上添加一个
名称属性,然后检查表单是否已提交。
这是我所说的一个演示

<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.";
    }
}

 ?>

你多大了?

您可以将
名称
属性添加到“提交”按钮,然后检查表单是否已提交。您的问题是,当您第一次访问页面
$\u POST
时,页面为空,因此
$age
将为
,这将使您的比较失败;因此,您的代码输出“您已经足够大了,可以看电影了”。您需要更改
$age
的分配,以通过在尝试使用它之前检查
$\u POST['age']
是否已设置来停止这种情况,例如
$age=isset($\u POST['age'])$_POST['age']:“”
或者如果您使用的是PHP7
$age=$\u POST['age']??"";Sifat Haque非常感谢,我希望它能正常工作。