Problems with validation

Discussion in 'PHP' started by dtm32236, Mar 3, 2009.

  1. #1
    Hey guys,

    So, this script simply checks a form with the following fields:
    first name, last name, email, shirt size, gender, city and state

    And makes sure that no fields are empty, then makes sure the email address is valid, and then it checks against a database for duplicate email entries.

    I had this working at some point, but now it's not and I can't figure out why.

    Here's the code:
    <?php
    	$conn = mysql_connect("localhost", "***", "***");
        mysql_select_db("***", $conn);
    	
    	#strip inputs of html and other charaters
    	$email = trim($_POST['formEmail']);
    	$email = strip_tags($email);
    	$email = htmlspecialchars($email);
        $email = mysql_real_escape_string($email);
    	
    	$fname = trim($_POST['formFname']);
    	$fname = strip_tags($fname);
    	$fname = htmlspecialchars($fname);
        $fname = mysql_real_escape_string($fname);
    	
    	$lname = trim($_POST['formLname']);
    	$lname = strip_tags($lname);
    	$lname = htmlspecialchars($lname);
        $lname = mysql_real_escape_string($lname);
    	
    	$city = trim($_POST['formCity']);
    	$city = strip_tags($city);
    	$city = htmlspecialchars($city);
        $city = mysql_real_escape_string($city);
    
    	$shirt = $_POST['formShirt'];
    	$gender = $_POST['formGender'];
    	$state = $_POST['formState'];
    	
    	#set validation to false
    	$validFields == "false";
    	$validEmail == "false";
    	$validDupe == "false";
    	
    	#check for missing fields
    	if (($email == '') OR ($fname == '') OR ($lname == '') OR ($shirt == '') OR ($gender == '') OR ($city == '') OR ($state == '')) {
    		$validFields == "false";
    		echo ("A field was left blank.");
    	}
    	else {
    		$validFields == "true";
    	}
    	
    	#validate email		
    	if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
    		$validEmail == "true";
    	}
    	else {
    		$validEmail == "false";
    		echo ("Invalid email address.");
    	}
    	
    	#check for duplicate emails in database	
    	$dupeCheck = mysql_query("SELECT * FROM `registered` WHERE email = '". $email . "'");	
    	if (mysql_num_rows($dupeCheck) > 0) {
    		$validDupe == "false";
    		echo ("Email already in use.");
    	}
    	else {
    		$validDupe == "true";
    	}
    
    	if (($validFields == "true") AND ($validEmail == "true") AND ($validDupe == "true")) {
    		mysql_query("INSERT INTO `registered` (`email`, `f_name`, `l_name`, `shirt`, `gender`, `city`, `state`) VALUES('{$email}', '{$fname}', '{$lname}', '{$shirt}', '{$gender}', '{$city}', '{$state}')");
    		echo ("success!");
    	}
    	else
    		echo ("fail.");
        
      mysql_close($conn);
    ?>
    PHP:
    This used to work, but now it only returns "fail.", unless I make the form invalid (submitting with a blank field, etc), then it returns the error. Maybe it has something to do with datatypes (true/false)? I have no idea.

    Can anyone see what's wrong with this code?

    As you can see, I'm a complete noob at PHP... I'm just starting to learn.
    This code is a mess, isn't it? :(

    I'm sure there's much easier ways of writing this using loops, functions, etc... and I'm open to suggestion and criticism.
     
    dtm32236, Mar 3, 2009 IP
  2. Techmonkey

    Techmonkey Active Member

    Messages:
    107
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #2
    cant see it straight off, but add some echo's in to help you locate the problem:

    
    <?php
        $conn = mysql_connect("localhost", "***", "***");
        mysql_select_db("***", $conn);
       
        #strip inputs of html and other charaters
        $email = trim($_POST['formEmail']);
        $email = strip_tags($email);
        $email = htmlspecialchars($email);
        $email = mysql_real_escape_string($email);
       
        $fname = trim($_POST['formFname']);
        $fname = strip_tags($fname);
        $fname = htmlspecialchars($fname);
        $fname = mysql_real_escape_string($fname);
       
        $lname = trim($_POST['formLname']);
        $lname = strip_tags($lname);
        $lname = htmlspecialchars($lname);
        $lname = mysql_real_escape_string($lname);
       
        $city = trim($_POST['formCity']);
        $city = strip_tags($city);
        $city = htmlspecialchars($city);
        $city = mysql_real_escape_string($city);
    
        $shirt = $_POST['formShirt'];
        $gender = $_POST['formGender'];
        $state = $_POST['formState'];
       
        #set validation to false
        $validFields == "false";
        $validEmail == "false";
        $validDupe == "false";
       
        #check for missing fields
        if (($email == '') OR ($fname == '') OR ($lname == '') OR ($shirt == '') OR ($gender == '') OR ($city == '') OR ($state == '')) {
            $validFields == "false";
            echo ("A field was left blank.");
        }
        else {
            $validFields == "true";
        }
       
        #validate email  
        if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
            $validEmail == "true";
        }
        else {
            $validEmail == "false";
            echo ("Invalid email address.");
        }
       
        #check for duplicate emails in database 
        $dupeCheck = mysql_query("SELECT * FROM `registered` WHERE email = '". $email . "'");   
        if (mysql_num_rows($dupeCheck) > 0) {
            $validDupe == "false";
            echo ("Email already in use.");
        }
        else {
            $validDupe == "true";
        }
    
        if (($validFields == "true") AND ($validEmail == "true") AND ($validDupe == "true")) {
            mysql_query("INSERT INTO `registered` (`email`, `f_name`, `l_name`, `shirt`, `gender`, `city`, `state`) VALUES('{$email}', '{$fname}', '{$lname}', '{$shirt}', '{$gender}', '{$city}', '{$state}')");
            echo ("success!");
        }
        else
            echo ("fail.");
    echo "Valid Fieds = $validFields";
    echo "Valid Email = $validEmail"';
    echo "Valid Dupe = $validDupe";
       
      mysql_close($conn);
    ?>
    
    
    Code (markup):
    Those extra echo's will help you locate the problem
     
    Techmonkey, Mar 3, 2009 IP
  3. dtm32236

    dtm32236 Guest

    Messages:
    320
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks Techmonkey.

    I tried that before, and they return nothing:

    Valid Fieds =
    Valid Email =
    Valid Dupe =

    That doesn't make sense to me...
     
    dtm32236, Mar 3, 2009 IP
  4. GreatMetro

    GreatMetro Peon

    Messages:
    117
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You're using a comparator ( == ) for assignment.

    Use == to compare:

    if ($a == $b)

    and = to assign

    $b = "hi"

    See highlighted below -- should all be "=" instead of "=="


    <?php
    $conn = mysql_connect("localhost", "***", "***");
    mysql_select_db("***", $conn);

    #strip inputs of html and other charaters
    $email = trim($_POST['formEmail']);
    $email = strip_tags($email);
    $email = htmlspecialchars($email);
    $email = mysql_real_escape_string($email);

    $fname = trim($_POST['formFname']);
    $fname = strip_tags($fname);
    $fname = htmlspecialchars($fname);
    $fname = mysql_real_escape_string($fname);

    $lname = trim($_POST['formLname']);
    $lname = strip_tags($lname);
    $lname = htmlspecialchars($lname);
    $lname = mysql_real_escape_string($lname);

    $city = trim($_POST['formCity']);
    $city = strip_tags($city);
    $city = htmlspecialchars($city);
    $city = mysql_real_escape_string($city);

    $shirt = $_POST['formShirt'];
    $gender = $_POST['formGender'];
    $state = $_POST['formState'];

    #set validation to false
    $validFields == "false";
    $validEmail == "false";
    $validDupe == "false";

    #check for missing fields
    if (($email == '') OR ($fname == '') OR ($lname == '') OR ($shirt == '') OR ($gender == '') OR ($city == '') OR ($state == '')) {
    $validFields == "false";
    echo ("A field was left blank.");
    }
    else {
    $validFields == "true";
    }

    #validate email
    if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
    $validEmail == "true";
    }
    else {
    $validEmail == "false";
    echo ("Invalid email address.");
    }

    #check for duplicate emails in database
    $dupeCheck = mysql_query("SELECT * FROM `registered` WHERE email = '". $email . "'");
    if (mysql_num_rows($dupeCheck) > 0) {
    $validDupe == "false";
    echo ("Email already in use.");
    }
    else {
    $validDupe == "true";
    }

    if (($validFields == "true") AND ($validEmail == "true") AND ($validDupe == "true")) {
    mysql_query("INSERT INTO `registered` (`email`, `f_name`, `l_name`, `shirt`, `gender`, `city`, `state`) VALUES('{$email}', '{$fname}', '{$lname}', '{$shirt}', '{$gender}', '{$city}', '{$state}')");
    echo ("success!");
    }
    else
    echo ("fail.");

    mysql_close($conn);
    ?>
     
    GreatMetro, Mar 6, 2009 IP
  5. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #5
    Cleaned it up a bit. Without doing a error check then I can't tell exactly what is going on. Did you get any error messages when running the code?

    <?php
    
      session_start();
      if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) { ob_start("ob_gzhandler"); } else { ob_start(); }
      error_reporting(E_ALL);
      ini_set("display_errors", 1);
      
      $conn = mysql_connect("localhost", "***", "***");
      mysql_select_db("***", $conn);
      
      function clean($str)
      {
          if ($str == '')
          {
              return $str;
          }
          $str = trim($str);
          $str = strip_tags($str);
          $str = htmlspecialchars($str);
          $str = mysql_real_escape_string($str);
          return $str;
      }
      /* strip inputs of html and other charaters */
      $email = clean($_POST['formEmail']);
      $fname = clean($_POST['formFname']);
      $lname = clean($_POST['formLname']);
      $city = clean($_POST['formCity']);
      $shirt = clean($_POST['formShirt']);
      $gender = clean($_POST['formGender']);
      $state = clean($_POST['formState']);
      
      /*set validation to false*/
      $validFields = false;
      $validEmail = false;
      $validDupe = false;
      
      /* check for missing fields */
      if (($email == '') || ($fname == '') || ($lname == '') || ($shirt == '') || ($gender == '') || ($city == '') || ($state == ''))
      {
          $validFields = false;
          echo 'A field was left blank.';
      }
      else
      {
          $validFields = true;
      }
      
      
      /* validate email */
      if ($email == '')
      {
          $validEmail = false;
      }
      elseif (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
      {
          $validEmail = true;
      }
      else
      {
          $validEmail = false;
          echo 'Invalid email address.';
      }
      
      /* check for duplicate emails in database  */
      $dupeCheck = mysql_query("SELECT `email` FROM `registered` WHERE `email` = '$email' limit 1");
      if (mysql_num_rows($dupeCheck) > 0)
      {
          $validDupe = false;
          echo 'Email already in use.';
      }
      else
      {
          $validDupe = true;
      }
      
      if (($validFields == true) and ($validEmail == true) and ($validDupe == true))
      {
          mysql_query("
            INSERT INTO `registered` SET
           `email` = '{$email}',
           `f_name` =  '{$fname}',
           `l_name` = '{$lname}',
           `shirt` = '{$shirt}',
           `gender` = '{$gender}',
           `city` = '{$city}',
           `state` = '{$state}';");
          
          echo 'success!';
      }
      else
      {
          echo 
    'Failed:<br />
    validFields = $validFields;<br />
    validEmail = $validEmail;<br />
    validDupe = $validDupe;<br />
    ';
    
      }
      
      mysql_close($conn);
    ?>
    PHP:
     
    exodus, Mar 6, 2009 IP
  6. dtm32236

    dtm32236 Guest

    Messages:
    320
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Wow - you guys rock.

    GreatMetro, you're right. I was confusing == and =
    This definitely clears things up.

    And Exodus, thanks for cleaning it up like that. I should've known to use a function to 'clean' the input fields. Thanks for the tip. That'll save sooo much time in the future.

    Thanks again for all the help everyone... it's working perfectly now!
     
    dtm32236, Mar 11, 2009 IP
  7. adstiger

    adstiger Peon

    Messages:
    409
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #7
    You should check it with var_dump() function for detecting the errors. Remember to go step by step in code optimization.
     
    adstiger, Mar 11, 2009 IP
  8. dtm32236

    dtm32236 Guest

    Messages:
    320
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Oh, nice. So var_dump would return the data type too - so I would've seen that it wasn't assigning 'true' or 'false' to the variable. That makes sense.

    Thanks adstiger. I'll keep that in mind.
     
    dtm32236, Mar 11, 2009 IP
  9. adstiger

    adstiger Peon

    Messages:
    409
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #9
    You are welcome @dtm32236
     
    adstiger, Mar 11, 2009 IP