php 如何检查表单中的任何字段是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14250880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:56:38  来源:igfitidea点击:

How to check if any fields in a form are empty

phphtmlforms

提问by Travis Nabbefeld

I am building a login system for a website of mine and I need a way of checking if all the fields in a form are filled out. I am also having a problem with an error message say my email is not in the correct format.

我正在为我的网站构建一个登录系统,我需要一种方法来检查表单中的所有字段是否都已填写。我也遇到了错误消息的问题,说我的电子邮件格式不正确。

<?php
$con = mysql_connect(localhost, 262096, 9201999);
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("262096", $con);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST['passwordconf'];
$email = $_POST['email'];
$securityq = $_POST['securityq'];
$qanswer = $_POST['qanswer'];

if(empty($firstname) || empty($lastname) || empty($username) || empty($password) ||
    empty($passwordconf) || empty($email) || empty($securityq) || empty($qanswer))
{
    echo "You did not fill out the required fields.";
}

$uname = "SELECT * FROM users WHERE username='{$username}'";
$unamequery = mysql_query($uname) or die(mysql_error());
if(mysql_num_rows($unamequery) > 0) 
{
    echo "The username you entered is already taken";
}

$emailfind = "SELECT * FROM users WHERE email='{$email}'";
$emailquery = mysql_query($emailfind) or die(mysql_error());
if(mysql_num_rows($emailquery) > 0)
{
    echo "The email you entered is already registered";
}

if($password != $passwordconf)
{
    echo "The passwords you entered do not match";
}

$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
    echo "The email you entered is not in name@domain format";
}

回答by Chris Visser

When using large forms I recommend creating an array with the form fields:

使用大型表单时,我建议使用表单字段创建一个数组:

$fields = array('firstname', 'lastname', 'username', 'password', 'passwordconf', 'email', 'securityq', 'qanswer');

$error = false; //No errors yet
foreach($fields AS $fieldname) { //Loop trough each field
  if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
    echo 'Field '.$fieldname.' misses!<br />'; //Display error with field
    $error = true; //Yup there are errors
  }
}

if(!$error) { //Only create queries when no error occurs
  //Create queries....
}

回答by muffy

By looking at your code it looks like you are using server side validation for basic validations.

通过查看您的代码,您似乎正在使用服务器端验证进行基本验证。

why don't you try client side validation using Jquery

为什么不尝试使用 Jquery 进行客户端验证

http://docs.jquery.com/Plugins/Validation#Options_for_the_validate.28.29_method

http://docs.jquery.com/Plugins/Validation#Options_for_the_validate.28.29_method

回答by atlas

First of all use mysql_real_escape_string() to avoid MYSQL injections:

首先使用 mysql_real_escape_string() 来避免 MYSQL 注入:

...
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
...

And to check if a field is empty in order to return an error or a message just do this (brief example):

并检查字段是否为空以返回错误或消息,只需执行以下操作(简短示例):

if (!(empty($_POST['firstname']))){
    execute some code....
}
else {
     execute some code... 
}

Hope that helps

希望有帮助

回答by Tristan

If you are doing anything with a database you should sanitize your input. As for checking the POST values. If you need ALL the posts on that page to be completed, you could try looping through the $_POST and checking each one. You should also stop execution if you are echoing that there was an error. And PLEASE do not listen to people saying use javascript for this, you need strong server side validation before you worry about javascript!

如果您正在对数据库做任何事情,您应该清理您的输入。至于检查 POST 值。如果您需要完成该页面上的所有帖子,您可以尝试遍历 $_POST 并检查每个帖子。如果您回应有错误,您也应该停止执行。并且请不要听人们说为此使用 javascript,在担心 javascript 之前,您需要强大的服务器端验证!

foreach($_POST as $key => $value) {
  if(empty($value)) {
    echo "Error, not all values given.";
    die;
  }
}

But I would advise you to check individual posts in more depth also. Make sure their username and password have the right characters.. and use mysql_escape_string($str)if you are querying it to the database.

但我建议您也更深入地检查个别帖子。确保他们的用户名和密码具有正确的字符......并mysql_escape_string($str)在您向数据库查询时使用。

回答by Charles

Use a simple if statement to see if any of the fields the user has submitted are empty. For example, to check if the username field is empty:

使用简单的 if 语句查看用户提交的任何字段是否为空。例如,要检查用户名字段是否为空:

$username = $_POST['username'];
if ($username == "") {
echo "Username field is empty! <a href='page.php'>Go Back</a>
{
else {
echo "The username field has text in it. It is not empty.";
}

回答by Hanky Panky

There are multiple issues with this code:

此代码存在多个问题:

  1. It is not secure.
  2. You are displaying error messages but still code continues to execute, so it will execute your select query even when username is empty.
  3. Due to reason two, almost all your queries below can fail.
  1. 它不安全。
  2. 您正在显示错误消息,但代码仍在继续执行,因此即使用户名为空,它也会执行您的选择查询。
  3. 由于原因二,您下面的几乎所有查询都可能失败。

So, you have to stop here

所以,你必须停在这里

if(empty($firstname) || empty($lastname) || empty($username) || empty($password) || empty($passwordconf) || empty($email) || empty($securityq) || empty($qanswer))
    {
    echo "You did not fill out the required fields.";
    die();  // Note this
    }

回答by Chris Visser

U might want to use the isset() and empty() function

你可能想使用 isset() 和 empty() 函数

//! means NOT so: exists and NOT empty
if(isset($_POST['firstname']) && !empty($_POST['firstname'])) {
  $firstname = $_POST['firstname'];

  //Do something with $firstname
}

Keep in mind that the above code is just an example. Its nice to start with, but in realtime you will have to do alot more about security. Also make sure to let the code kill or skip the queries when validation fails

请记住,上面的代码只是一个示例。开始时很好,但在实时情况下,您将不得不在安全方面做更多的事情。还要确保在验证失败时让代码终止或跳过查询

回答by smehsoud

       if(in_array("",$_POST)){
         //this will check the whole post data if any field is empty.
            echo 'form is empty'; 
            echo 'some error message';
            exit;
        }else{
            echo "form is not empty";
            //some code
        }