我真的很新的PHP,所以听我说。 我创建了一个简单的页面,其中包含一个表单,用于验证您发送的数据是否可以发送,但它在我输入任何内容之前给出了验证错误。下面是代码:
<html>
<body>
<form action="first.php" method="post">
Username:<input type="text" name="username"><br />
Password:<input type="password" name="password"><br />
<input type="submit" name="submit"><br />
</form>
<?php
$errors = array();
$username = $_POST['username'];
$password = $_POST['password'];
$errors = array();
if(!isset($username) || empty($username)){
$errors = "Empty username<br />";
}
if ($username > 10){
$errors['username'] = "Username out of range<br />";
}
if (!empty($errors)){
echo "Error<br />";
print_r ($errors);
}
?>
</body>
</html>
答案 0 :(得分:0)
将PHP代码包装到if()
条件:
if( isset($_POST['submit']) )
{
$errors = array();
(...)
}
如果没有这个,即使没有提交表单,也会执行您的代码。
答案 1 :(得分:0)
试试这个:
<html>
<body>
<form action="first.php" method="post">
Username:<input type="text" name="username"><br />
Password:<input type="password" name="password"><br />
<input type="submit" name="submit"><br />
</form>
<?php
if(isset($_POST['submit']))
{
$errors = array();
$username = $_POST['username'];
$password = $_POST['password'];
$errors = array();
if(!isset($username) || empty($username)){
$errors = "Empty username<br />";
}
if ($username > 10){
$errors['username'] = "Username out of range<br />";
}
if (!empty($errors)){
echo "Error<br />";
print_r ($errors);
}
}
?>
</body>
</html>