How to display multiple error messages simultaneously in form?

Asked

Viewed 1,507 times

1

I’m trying to get my log page to show all forgotten fields messages together as in this example:

erros

But it only shows in parts:

1 - "Username already exists" and "Email already exists" or

2 - "Please Insert a username", "Please Insert a password" and "Please Insert a email" or

3 - "Username must have Less than 16 characters" and "Password must have 8 or more characters"

Is there any solution to this?

<?php
$page = "Register";
include "header.php";

if(isset($_POST["register"])){

$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];

if(!empty($username) && !empty($password) && !empty($email)){

    if(strlen($username) < 17 && strlen($password) > 7){

        $checkusername = mysql_query("SELECT `id` FROM `database`.`user` WHERE `username` = '".$username."'");
        $checkemail = mysql_query("SELECT `id` FROM `database`.`user` WHERE `email` = '".$email."'");

        if(mysql_num_rows($checkusername) == 0 && mysql_num_rows($checkemail) == 0){

            $insert = mysql_query("INSERT INTO `database`.`user`(`username`,`password`,`email`) VALUES ('".$username."','".$password."','".$email."')") or die(mysql_error());
            ?><p><?php echo "You are Registered"; ?></p><?php
        }
        else{
            if(mysql_num_rows($checkusername) > 0){
                $error[] = "Username already exists";
            }
            if(mysql_num_rows($checkemail) > 0){
                $error[] = "Email already exists";
            }
            foreach($error as $value){
                ?><p><?php echo "'".$value."'<br>"; ?></p><?php
            }
        }
    }
    else{
        if(strlen($username) > 16){
            $error[] = "Username must have less than 16 characters";
        }
        if(strlen($password) < 8){
            $error[] = "Password must have 8 or more characters";
        }
        foreach($error as $value){
            ?><p><?php echo "'".$value."'<br>"; ?></p><?php
        }
    }
}
else{

    if(empty($username)){
        $error[] = "Please insert a username";
    }
    if(empty($password)){
        $error[] = "Please insert a password";
    }
    if(empty($email)){
        $error[] = "Please insert a email";
    }
    foreach ($error as $value) {
        ?><p><?php echo "'".$value."'<br>"; ?></p><?php
    }
}
}
?>

<div id="loginform">
    <form name="loginform" method="post">
        <table cellpadding="0" id="tb">
            <tr>
            <td colspan="2"><div class="loginheader"><h2>Register</h2></div></td>
            </tr>
        </table>
        <table cellpadding="0" id="REGOPTIONS">
            <tr>
            <td class="field">Username:</td>
            <td><input type="text" class="text" name="username"></td>
            </tr>
            <tr>
            <td class="field">Password:</td>
            <td><input type="password" class="text" name="password"></td>
            </tr>
            <tr>
            <td class="field">Email:</td>
            <td><input type="email" class="text" name="email"></td>
            </tr>
        </table>
        <table cellpadding="0">
            <tr>
            <td class="field"></td>
            <td><input type="submit" class="submitbutton" name="register" value="Register" /></td>
            </tr>
        </table>
    </form>
</div>

<?php
include "footer.php";
?>

2 answers

3


You can use separate variables for each type of error, and index them in the respective fields.

So that messages can appear simultaneously, I refactored your code, allowing the treatment of each field separately:

<?php
   $page = 'Register';
   include 'header.php';

   $user_error='';
   $mail_error='';
   $pass_error='';

   if( isset( $_POST['register'] ) ) {
      $username = $_POST['username'];
      $password = $_POST['password'];
      $email = $_POST['email'];

      // Tratamento de erros do username:

      if( empty( $username ) ) {
         $user_error = 'Please insert an username';
      } elseif ( strlen( $username ) ) > 16
         $user_error = 'Username must have less than 17 characters';
      } else {
         // Essa linha abaixo é sujeita a SQL Injection, cuidado!
         $checkusername = mysql_query("SELECT `id` FROM `database`.`user` WHERE `username` = '".$username."'");
         if(mysql_num_rows($checkusername) > 0) {
            $user_error = 'Username already exists';
         }
      }

      // Tratamento de erros da senha:

      if( empty( $password ) ) {
         $pass_error = 'Please insert a password';
      } elseif( strlen( $password ) < 8 ) {
         $pass_error = 'Password must have 8 or more characters';
      }

      // Tratamento de erros do email:

      if( empty( $email ) ) {
         $mail_error = 'Please insert an email';
      } else {
         // Essa linha abaixo é sujeita a SQL Injection, cuidado!
         $checkemail = mysql_query("SELECT `id` FROM `database`.`user` WHERE `email` = '".$email."'");
         if( mysql_num_rows( $checkemail ) > 0 ){
            $mail_error = 'Email already exists';
         }
      }
   }

   // Se não setamos nenhum erro, e o formulário foi enviado, podemos ir para o insert:
   if empty( $user_error )
   && empty( $mail_error )
   && empty( $pass_error )
   && isset( $_POST['register'] ) ) {
      $insert = mysql_query("INSERT INTO `database`.`user`(`username`,`password`,`email`) VALUES ('".$username."','".$password."','".$email."')") or die(mysql_error());
?>
<div id="sucesso">
   <h3>You are registered!</h3>
   <p>(aqui você pode por instruçoes, ou a mensagem que quiser, no caso do sucesso)</p>
</div>
<?php
   } else {
      // caso contrário, mostramos o form, e opcionalmente os erros encontrados:
      $user_error=empty($user_error)?'Username:' : '<b>'.htmlEntities($user_error).'</b>';
      $mail_error=empty($mail_error)?'Email:' : '<b>'.htmlEntities($email_error).'</b>';
      $pass_error=empty($pass_error)?'Password:' : '<b>'.htmlEntities($pass_error).'</b>';
      // O formulario está dentro deste else:
?>

<div id="loginform">
   <form name="loginform" method="post">
      <table cellpadding="0" id="tb">
         <tr>
            <td colspan="2"><div class="loginheader"><h2>Register</h2></div></td>
         </tr>
      </table>
      <table cellpadding="0" id="REGOPTIONS">
         <tr>
            <td class="field"><?php echo $user_error; ?></td>
            <td><input type="text" class="text" name="username"></td>
         </tr>
         <tr>
            <td class="field"><?php echo $pass_error; ?></td>
            <td><input type="password" class="text" name="password"></td>
         </tr>
         <tr>
            <td class="field"><?php echo $mail_error; ?></td>
            <td><input type="email" class="text" name="email"></td>
         </tr>
      </table>
      <table cellpadding="0">
         <tr>
            <td class="field"></td>
            <td><input type="submit" class="submitbutton" name="register" value="Register" /></td>
         </tr>
      </table>
   </form>
</div>

<?php
   } // Fechando o else acima

   include "footer.php";
?>

Thus, each error will be shown in its own field. This solution seems suitable for your case, because there is only one error of each type being shown at the same time in your code (user, password and email).

If you like, the same ifs can be used and adapted to apply the @Otto solution, which is good if you want all errors presented in a single block.

  • very good @Bacco

  • @Lukaz11: See in this answer how to use the mysqli to avoid SQL Injection, and quote problems in the fields: http://answall.com/a/14757/70

1

<p><?php echo "'".$value."'<br>"; ?></p>

swap for

$error =. "<p>".$value."<br></p>";

at the end of the echo $error loop;

  • I tried this code but nothing happens.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.