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

时间:2022-11-24 19:44:00

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";
}

8 个解决方案

#1


12  

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....
}

#2


2  

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

#3


2  

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

希望这有助于

#4


1  

There are multiple issues with this code:

这个代码有很多问题:

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

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
    }

#5


1  

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.";
}

#6


1  

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)。

#7


0  

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

请记住,上面的代码只是一个示例。一开始很好,但实际上你需要做更多关于安全性的事情。还要确保在验证失败时让代码终止或跳过查询

#8


0  

       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
        }

#1


12  

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....
}

#2


2  

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

#3


2  

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

希望这有助于

#4


1  

There are multiple issues with this code:

这个代码有很多问题:

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

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
    }

#5


1  

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.";
}

#6


1  

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)。

#7


0  

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

请记住,上面的代码只是一个示例。一开始很好,但实际上你需要做更多关于安全性的事情。还要确保在验证失败时让代码终止或跳过查询

#8


0  

       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
        }