好的,我有一个带有1个输入和提交按钮的表单。现在我使用if / else语句为该输入做出三个可接受的答案。是的,不,或其他任何东西。这个if / else工作的东西是代码在加载页面后立即踢出else函数。我希望在用户输入之前没有任何内容,然后它会显示三个答案中的一个。
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
答案 0 :(得分:2)
只需在设置POST值时调用代码即可。这样它只会在提交表单时执行代码(设置为$_POST['senddata']
):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
答案 1 :(得分:1)
只需将验证放在第一个if
语句中,如下所示:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
答案 2 :(得分:0)
当您加载页面时,浏览器正在发出GET请求,当您提交表单时,浏览器正在发出POST请求。您可以使用以下方式检查提出的请求:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
将它放在您的表单处理代码周围,以防止它在GET请求上执行。