我正在尝试创建一条错误消息,以防用户没有正确填写字段,但是在第一次加载页面时,我希望它不显示任何错误消息,但是它会在按下按钮之前执行代码,因此它会在用户执行任何操作之前显示一条错误消息...
我该如何解决呢?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>ROCK PAPER SCISSORS GAME</title>
</head>
<style media="screen">
input[type=text], select{
width: 100%;
padding: 5px;
margin: 10px;
height: 20px;
border-radius: 5px;
}
input[type=password]{
width: 100%;
padding: 5px;
margin: 10px;
height: 20px;
border-radius: 5px;
}
input[type=submit]{
margin-left: 10px;
width: 150px;
height: 30px;
background-color: #6DC066;
border-radius: 15px;
}
input[type=submit]:hover {
background-color: #45a049;
}
input:hover {
border-color: #26c8ff;
border-width: 3px;
}
</style>
<?php
$responseMessage = "";
if (!empty($_POST["email"]) && !empty($_POST["pass"])){
$responseMessage = "they are set";
} else if (empty($_POST["email"]) && empty($_POST["pass"])){
$responseMessage = "please, fill in all fields";
}
?>
<body>
<div style="width: 550px;">
<h1 style="margin-left: 10px;">LOGIN ROCK SCISSORS GAME:</h1>
<p style="margin-left: 10px; color: red"><?= $responseMessage; ?></p>
<form class="" action="index.php" method="post">
<label style="margin: 10px;" for="email" >Email:</label>
<input type="text" name="email" value="" placeholder="Type your email">
<label style="margin: 10px;" for="pass">Password:</label>
<input type="password" name="pass" value="" placeholder="Type your password">
<input type="submit" name="login" value="login">
</form>
</div>
</body>
</html>
答案 0 :(得分:3)
在运行代码之前,请检查表单是否已提交(通过检查“提交”按钮是否存在)。
<?php
$responseMessage = "";
// This check will only evaluate as true if $_POST['login'] exits and isn't null,
// which will only be the case when the form been submitted.
if (isset($_POST['login'])) {
if (!empty($_POST["email"]) && !empty($_POST["pass"])){
$responseMessage = "they are set";
} else if (empty($_POST["email"]) && empty($_POST["pass"])){
$responseMessage = "please, fill in all fields";
}
}
?>
答案 1 :(得分:1)
您需要检查发帖请求
<?php
$responseMessage = "";
if ($_POST && $_POST["login"]){
if (!empty($_POST["email"]) && !empty($_POST["pass"])){
$responseMessage = "they are set";
}else if (empty($_POST["email"]) || empty($_POST["pass"])){
// i changed && to || (or)
$responseMessage = "please, fill in all fields";
}
}
?>