Jump to content

i need help woth my form validation [;s


Michael_Baxter

Recommended Posts

Hi I am working on a project and I am struggling a little with it

I am new to PHP but very determined to learn,

at this point I am working on my user registration form as this seems the right place to start before I an have a user on my site they need to be able to register to the site,

so I built a very simple form [ for demo use only]

ok so now I have my form and database for the user info to post to

so far this is all fully working a user goes to my site fills out the registration details and clicks submit the info is posted to my database

that's great however I have now added some PHP validation coding to my form which also works mostly,

the issue I am having right now is that with how I have made my code it does not matter if the user does not submit valid data the form still posts to my database

for EG, my fields are: fname, lname, contact, gender, picture user name, password

all fields at this time are required and can accept alphanumeric combo

but if the user leaves blank or types in illegal key presses thr form will still post to my database and show the errors on the page  

I am trying to find a way to make it so that my code stops or gives the error message that the details are incorrect without submitting to the database

here is my codes so far:

<?php
ini_set("display_errors",1);
error_reporting(E_ALL);

    // define variables and set to empty values
$fnameErr = $lnameErr = $mnameErr = $addressErr = $contactErr = $picErr = $usernameErr = $passwordErr = "";
$fname = $lname = $mname = $address = $contact = $pic = $username = $password = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["fname"])) {
     $fnameErr = "First Name is required";
   } else {
     $fname = test_input($_POST["fname"]);
     // check if first name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
       $fnameErr = "url.location'/index3.php'"; 
     }
   }
   
   if (empty($_POST["lname"])) {
     $lnameErr = "Last Name is required";
   } else {
     $lname = test_input($_POST["lname"]);
     // check if last name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
       $lnameErr = "Only letters and white space allowed"; 
     }
   }

   if (empty($_POST["mname"])) {
     $mnameErr = "Gender is required";
   } else {
     $mname = test_input($_POST["mname"]);
     // check if last name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$mname)) {
       $mnameErr = "Only letters and white space allowed"; 
     }
   }

   if (empty($_POST["address"])) {
     $addressErr = "Address is required";
   } else {
     $address = test_input($_POST["address"]);
     // check if last name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z0-9 ]*$/",$address)) {
       $addressErr = "Only letters numbers and white space allowed"; 
     }
   }

   if (empty($_POST["contact"])) {
     $contactErr = "Contact Number is required";
   } else {
     $contact = test_input($_POST["contact"]);
     // check if last name only contains letters and whitespace
     if (!preg_match("/^[0-9 ]*$/",$contact)) {
       $contactErr = "Only numbers and white space allowed"; 
     }
   }

   if (empty($_POST["pic"])) {
     $picErr = "pic is required";
   } else {
     $pic = test_input($_POST["pic"]);
     // check if last name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z0-9 ]*$/",$pic)) {
       $picErr = "Only letters numbers and white space allowed"; 
     }
   }


   if (empty($_POST["username"])) {
     $usernameErr = "user Name is required";
   } else {
     $username = test_input($_POST["username"]);
     // check if last name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z0-9 ]*$/",$username)) {
       $usernameErr = "Only letters numbers and white space allowed"; 
     }
   }

   if (empty($_POST["password"])) {
     $passwordErr = "Pasword is required";
   } else {
     $passwrod = test_input($_POST["password"]);
     // check if last name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z0-9]*$/",$password)) {
       $passwrodErr = "Only letters and numbers allowed"; 
     }
   }
}
function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}


?>
<html>
    <head>
        <meta charset="utf-8">
        <title>Registration Form</title>
<style>
.error {color: #FF0000;}
</style>
    </head>
    <body>
    
        <form name="reg" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"  method="post">
            <table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
                <tr>
                    <td width="95"><div align="right">First Name:</div></td>
                    <td width="171"><input type="text" name="fname" />   <span class="error">* <?php echo $fnameErr;?></span></td>


                </tr>
                <tr>
                    <td><div align="right">Last Name:</div></td>
                    <td><input type="text" name="lname" />   <span class="error">* <?php echo $lnameErr;?></span></td>


                </tr>
                <tr>
                    <td><div align="right">Gender:</div></td>
                    <td><input type="text" name="mname" />   <span class="error">* <?php echo $mnameErr;?></span></td>


                </tr>
                <tr>
                    <td><div align="right">Address:</div></td>
                    <td><input type="text" name="address" />   <span class="error">* <?php echo $addressErr;?></span></td>


                </tr>
                <tr>
                    <td><div align="right">Contact No.:</div></td>
                    <td><input type="text" name="contact" />   <span class="error">* <?php echo $contactErr;?></span></td>


                </tr>
                <tr>
                    <td><div align="right">Picture:</div></td>
                    <td><input type="text" name="pic" />   <span class="error">* <?php echo $picErr;?></span></td>


                </tr>
                <tr>
                    <td><div align="right">Username:</div></td>
                    <td><input type="text" name="username" />   <span class="error">* <?php echo $usernameErr;?></span></td>


                </tr>
                <tr>
                    <td><div align="right">Password:</div></td>
                    <td><input type="password" name="password" />
                       <span class="error">* <?php echo $passwordErr;?></span></td>


                </tr>
                <tr>
                    <td><div align="right"></div></td>
                    <td><input name="submit" type="submit" value="Submit" /></td>
                </tr>
            </table>
        </form>
    </body>
    </html>

<?php

    if (isset($_POST['submit'] ) ) {
        $host_name  = "localhost";
        $database   = "**********simple_login";
        $user_name  = "*********";
        $pass   = "*********";
          
        $db = mysqli_connect( $host_name, $user_name, $pass, $database );   
          
        if (!$db)   
        {   
            die("Failed to connect to MySQL: " . mysql_error());   
        }
        
        // example of inserting data into that table: 
        $sql = "INSERT INTO simple_login(fname, lname, gender, address, contact, picture, username, password) " 
             . " VALUES( ?, ?, ?, ?, ?, ?, ?, ? )"; 
        
        $stmt = $db->prepare( $sql ); 
        if (!$stmt) 
        { 
            die("Failed to prepare statement: " . $sql); 
        } 

        $stmt->bind_param("ssssssss", $fname, $lname, $mname, $address, $contact, $pic, $username, $password); 
        
        if ( ! $stmt->execute() ) 
        { 
            die("Execution of bound statement failed: " . $stmt->error); 
        }
        
        echo "Inserted {$stmt->affected_rows} correctly.<hr/>"; 
        
        $db->close();


  }

?>        
Link to comment
Share on other sites

Couple items.  

Where you have error reporting, you could one or other, they're both doing the same thing.

 

The way the variables are being defined is odd.  I'm not sure that's valid code.  use a simple syntax that's common.  

$lname = "";

To exit your script on a failed condition, use:

if (empty($_POST["lname"])) {
     $lnameErr = "Last Name is required";
     exit();
   } else {
     ...
   }

Start with those changes and see where that gets you.  But to answer your question directly, use exit() or die() to end the script. then something like

$lnameErr = "Last Name Required.";
header ("Location error.php?err=$lnameErr"); //send to previous or error reporting page
exit();
Edited by rwhite35
Link to comment
Share on other sites

to solve most of your problems, of getting your code to display any validation errors and to not run your database code when there are errors, you need an easy way of remembering what errors were detected that you can also easily test to see if there are errors.

 

the best way of doing this is to use an array variable. as each error is detected, you would store the error message as an element in the array. to test at any point if there are errors, you would check if the array is empty or not. to display all the errors, you would loop over the non-empty array. also, by using an array to hold the errors, you won't need to initialize all the separate hard-coded error variables.

 

in fact, there was a recent similar thread, where the same suggestions were made - http://forums.phpfreaks.com/topic/294898-required-fields/?do=findComment&comment=1506734

Link to comment
Share on other sites

Just thought I'd drop my two cents in. I use the same syntax to set my variables to empty. Not only is it legal code, it's clean.

 // define variables and set to empty values
$fnameErr = $lnameErr = $mnameErr = $addressErr = $contactErr = $picErr = $usernameErr = $passwordErr = "";
$fname = $lname = $mname = $address = $contact = $pic = $username = $password = "";

I use it that way in all my code. Even the PHP Cookbook I have shows that. So you're good to go there :)

Link to comment
Share on other sites

@rwhite35, the two lines setting error_reporting/display_errors are two different settings and both are necessary to insure that all run-time errors are reported and that those reported errors are displayed and the lines initializing the variables are technically correct, but unnecessary and even error prone, as it requires you to type and then maintain those statements to match the actual form.

 

the code suggested/at the linked to post, using arrays is the correct and clean way of dealing with sets of data.

Link to comment
Share on other sites

this is insane I am having more difficulty in getting to grips with the form validation than I did when I was reading P/W salt & hash

I understand this validation is more about my security and user accuracy,

I have to get ready to go to work now but I will be home in 6 hours or so then I will sit down and properly read through the above suggested post as that has some affective help in there thanks to everyone so far :D

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.