0

I can't see why the variable $errorMessage will not set with array errors.

I'm trying to make a form validation. This PHP is all at the top of the page register.php

This is the page I'm trying to work on. I hope I can resolve this!

<?php
   session_start();
   // include("includes/connect.php");
   include ("includes/html.php");


   if (isset($_POST['submit'])){
      $error = array(); 

      //username
      if (empty($_POST['username'])){
         $error[] = 'Please Enter a Username';
      }
      else if (ctype_alnum ($_POST['username'])){
         $userName = $_POST['username'];
      } 
      else {
         $error[] = 'Username Must Consist Letters and Numbers Only';
      }

      //email
      if (empty($_POST['email'])){
         $error[] = 'Please Enter an Email';
      } 
      else if (!preg_mach ("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)
↪*(\.[a-z]{2,3})$",$_POST['email'])) {
         $email = mysql_real_escape_string ($_POST['username']);
      } 
      else {
         $error[] = 'Your Email Address is Invalid';
      }

      //password
      if (empty($_POST['password'])){
         $error[] = 'Please Enter a password';
      } 
      else if ($_POST['password']!==$_POST['password2']){
         $error[] = 'Your Password Did Not Match';
      }
      else {
         $password = mysql_real_escape_string($_post['password']);
      }
   }

   if (empty ($error)){
      //good info
   }
   else {
      $errorMessage = '<span class="error">';
      foreach ($error as $key => $e){
         $errorMessage.= "$e";
      }
      $errorMessage.= '</span> <br /><br />';
   }

?>
3
  • Not an answer, but that's a pretty weak email validator. Commented Jun 14, 2012 at 15:48
  • Where do You print that $errorMessage variable? Commented Jun 14, 2012 at 15:49
  • Anyway, You could do this in a little prettier way: $errorMessage = '<span class="error">' . implode('<br />', $error) . '</span> <br /><br />'; echo $errorMessage;. Commented Jun 14, 2012 at 15:51

2 Answers 2

2

Your $error array is indexed, so you should use:

foreach ($error as $e){

}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah you're right. I do too much OOP I guess ;). I have checked your answer, it's correct +1.
0

Because you're checking if the error array IS EMPTY. If there's any error messages, it won't be empty, and you'll skip the entire message building block.

if (!empty ($error)){
    ^---- if NOT EMPTY

1 Comment

There is if-else in his code: if error is empty - not show errors, other way display all of them. I don't see error there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.