How to show multiple error messages simultaneously in form?

1

I'm trying to make my registration page show all messages from forgotten fields together like in this example:

Butitonlyshowsinparts:

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"

Are there any solutions 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";
?>
    
asked by anonymous 23.05.2014 / 16:50

2 answers

3

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

For messages to appear simultaneously, I've refactored your code, allowing each field to be treated 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 appropriate for your case, as there is only one error of each type being shown at the same time in your code (user, password and email).

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

    
23.05.2014 / 17:11
1
<p><?php echo "'".$value."'<br>"; ?></p>

Switch to

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

at the end of the loop echo $ error;

    
23.05.2014 / 16:52