我正在制作一个PHP和MySQL应用程序来练习我对编程的新兴之爱。我有一个登录脚本; HTML表单如下:
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username:
<input type="text" name="username" maxlength="60"><br />
Password:
<input type="password" name="password" maxlength="60"><br />
Confirm Password:
<input type="password" name="password_confirm" maxlength="60"><br />
<input type="submit" name="submit" value="Register"><br />
</form>
这继续进入PHP表单验证器:
<?php
$username_original = $_POST["username"];
$password_original = $_POST["password"];
$password_confirm_original = $_POST["password_confirm"];
//This makes sure they did not leave any fields blank
function FieldComplete($user, $password, $password_confirm) {
if (!isset($user, $password, $password_confirm) &&
$user && $password && $password_confirm == "" || " ") {
$field_confirm = false;
} else {
$field_confirm = true;
}
if ($field_confirm == true) {
echo "";
} else {
echo "You did not complete all the required fields.";
}
}
FieldComplete($username_original, $password_original, $password_confirm_original);
?>
我意识到为此制作一个功能似乎有点无用,但它与我想要的结果一样接近。
但是,此代码显示错误&#34;您没有填写所有必填字段。&#34;在加载页面时。我只想在按下注册按钮但仍有空白字段时显示该错误。
非常感谢任何建议或帮助。感谢StackOverflow社区!
答案 0 :(得分:3)
如果您只想在提交按钮时运行php代码,那么您需要在页面顶部查看该代码
if(isset($_POST["submit"]))
{
//form has been submitted
//do validation and database operation and whatever you need
} else {
//form has not been submitted
//print the form
}
答案 1 :(得分:0)
除了Fabio的回答,你可以像这样改进你的代码:
if(isset($_POST['submit'])){
$username_original = $_POST["username"];
$password_original = $_POST["password"];
$password_confirm_original = $_POST["password_confirm"];
$isComplete = FieldComplete($username_original, $password_original, $password_confirm_original);
if(!$isComplete){
echo "You did not complete all the required fields.";
}
}else{
//display the form
}
function FieldComplete($user, $password, $password_confirm) {
if (!isset($user, $password, $password_confirm) &&
$user && $password && $password_confirm == "" || " ") {
return false;
} else {
return true;
}
}