So I have created a PHP validation script. On test I filled and submitted the forms but so far $error returns undefined index and no data is set into the database. Can anyone take a look and give a second opinion on why its not functioning as intended? To my eye it all looks OK.

Otherwise my script runs OK (Insert into DB) it's just something about my validation script breaks it.

Thanks

<?php  

    if (isset($_POST['submit'])) {  

        if ($_POST['name'] != "") {  
            $_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);  
            if ($_POST['name'] == "") {  
                $errors .= 'Please enter a valid name.<br/><br/>';  
            }  
        } else {  
            $errors .= 'Please enter a name.<br/>';  
        }  

           if (isset($_POST['Submit'])) {  

        if ($_POST['address'] != "") {  
            $_POST['address'] = filter_var($_POST['address'], FILTER_SANITIZE_STRING);  
            if ($_POST['address'] == "") {  
                $errors .= 'Please enter a valid address<br/><br/>';  
            }  
        } else {  
            $errors .= 'Please enter a address.<br/>';  
        }  

           if (isset($_POST['postcode'])) {  

        if ($_POST['postcode'] != "") {  
            $_POST['postcode'] = filter_var($_POST['postcode'], FILTER_SANITIZE_STRING);  
            if ($_POST['postcode'] == "") {  
                $errors .= 'Please enter a valid name.<br/><br/>';  
            }  
        } else {  
            $errors .= 'Please enter a name.<br/>';  
        }  

        if (!$errors) {  



$name = $_POST['name'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$photo = $_POST['photo'];
$db1 = new dbmember();
$db1->openDB();
$numofrows = $db1->insert_member('', $name, $address, $postcode, $photo);
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";



$sql="SELECT * from member";
$result=$db1->getResult($sql);
echo "<table class='table table-hover'>";
echo "<tr><th>Member ID</th><th>Name</th><th>Address</th><th>Postcode</th><th>Photo</th></tr>";

  while($row = mysqli_fetch_assoc($result))
{
 echo "<tr>";
 echo "<td>{$row['mid']}</td><td>{$row['name']}</td>";
 echo "<td>{$row['address']}";
echo "<td>{$row['postcode']}";
 echo"<td><img height='80' width='120' src='{$row['photo'] }' /></td>";  
 echo "</tr>";
 }
 echo "</table>";


$db1->closeDB();
}


        }
        }
        }
            echo "Records updated!<br/><br/>";  
        } else {  
           echo '<div style="color: red">' . $errors . '<br/></div>';  // THIS is where the undefined index is flagged!
        }  

?>  

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" name="myform" class = "well" id="myform" onsubmit="return validateForm(  );">

Please fill in the fields to add a new member
<p></p>
<input type="text" class="span3" placeholder="Enter member name"name="name" value="<?php echo $_POST['name']; ?>" id="name" /><br />
<input type="text" class="span3"placeholder="Enter an address"name="address" value="<?php echo $_POST['address']; ?>" id="address" /><br />
<input type="text" class="span3"placeholder="Enter a postcode"name="postcode" value="<?php echo $_POST['postcode']; ?>"id="postcode" /><br />
<input type="text"class="span3" placeholder="Enter a picture (optional)"name="photo" /><br />
<p>
<button class="btn btn-primary" type="submit" value="Save" >Submit  </button>
</p>

</form>

Hi,

Here is a simple form validation I modified way back in 2007. Although i completely outgrown this script and I have written many fancy validation scripts ever since, I still honestly believe this can serve a really good sample script for you. I did a minor upgrade tonight so that it can function in PHP version 5.4 and above environment.

I adopted the implementation of filter_input_array php function, I found from unknown author. It was long time ago, I don't even remember the name of the blog. Actually, this my very first form validation written in procedural..

Please take notes how I avoided embedding my entire validation script within html tags. Although there are PHP embedded in the html form tags, those are the output from the function.

You can add more filters and other things as you desire. My aplology this function was written by a kid in 2007, but it worked flawlessly..

filename: checkForm.php

<?php
 ## original script credits unknown author
 ## updated by veedeoo 7/28/2013
 ## redefined filter functions
 ## upgraded the script to PHP 5.4 and > compliant

// things I modified in 2007
## created check_form function



function check_form(){

## we only want to process if request method is POST and ONLY if the submit button has been clicked or submitted!!!!
if (($_SERVER["REQUEST_METHOD"] == "POST") && (isset($_POST['submit']))){

## define filters: upgraded 7/28/2013
$php_filters = array(
    'fname' =>  FILTER_SANITIZE_STRING,
    'mname' =>  FILTER_SANITIZE_STRING,
    'lname' =>  FILTER_SANITIZE_STRING,
    'email' =>  FILTER_VALIDATE_EMAIL,
    'zip_code' =>  FILTER_SANITIZE_NUMBER_INT,
    'street' =>  FILTER_SANITIZE_STRING,
    'tel_no' =>  FILTER_SANITIZE_NUMBER_INT,
    'mobile' =>  FILTER_SANITIZE_NUMBER_INT,
);

## optional and are not required
$exemptions = array(
    'mname'       => "",  'zip_code'    => "",
    'street'    => "",  'mobile'     => "",
    );

## we create error messages, you can add more here based on the php_filters above.
$error_def = array(
    'fname'        =>"Missing or incorrect First Name",
    'lname'         =>"Missing or incorrect Last Name",
    'email'     =>"Missing or incorrect Email Address",
    'tel_no'  =>"Missing or incorrect Telephone Number",
    );

## sanitize input utilizing the php filters
$form_data = filter_input_array(INPUT_POST, $php_filters);

## we validate the form input
foreach ($form_data as $input => $value){

## double check and make sure we check inputs for false, null and empty values
if($value === FALSE || $value === NULL || $value == ""){

    ## we make sure to apply our exemptions
    if(!(array_key_exists($input, $exemptions) && $value == "")){
        $invalid_inputs[] = $input;
    }
}
}

## we unset the validation control if invalid_inputs[] is empty
if(empty ($invalid_inputs))
                {
                ## insert database function below

            ## return the output
            return array(false,$input,$invalid_inputs,$error_def = null,true,$form_data);

}
else {
return array(true,$input,$invalid_inputs,$error_def,true,$form_data);
}
}
}

To use the function above, include the mysqli wrapper class and then, and create an object inside the if statement as shown below (taken out from above)

if(empty ($invalid_inputs))
                {
                ## insert database object below
              $object = new Database();
              $query = 'your query here';

            ## return the output
            return array(false,$input,$invalid_inputs,$error_def = null,true,$form_data);

}

If you will be adding the mysqli object, then you must add a confirmation to the output..something like this..

## insert database object below
 $sucess = false;

        $db1 = new dbmember();
        $db1->openDB();
        $numofrows = $db1->insert_member($form_data['name'], $form_data['street'], $form_data['zip_code']); // i did not include the $photo , you must include it in the form.

if($numofrows){
    $sucess = true;
    ## return the output
            return array(false,$input,$invalid_inputs,$error_def = null,true,$form_data,$success);
}

modify the else statement to reflect success is equal to false

else {
$success = false;
return array(true,$input,$invalid_inputs,$error_def,true,$form_data,$success);
}

Your form page can be like this...

filename: form.php

<?php
include_once('checkForm.php');

$formchecks = check_form();
$form_data = false;
if($formchecks[4]){

## this creates a value in the form even if the input does not pass..to keep the user in cool mode.
$form_data = true;

}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>


<form action="" method="POST" >
<label for="fname">First Name*</label>
<input type="text" name="fname" id="first_name" value="<?php echo ($form_data===true? $formchecks[5]['fname'] : "");?>"/><br/>
<label for="mname">Middle Name</label>
<input type="text" name="mname" id="middle_name" value="<?php echo ($form_data===true? $formchecks[5]['mname'] : "");?>"/><br/>
<label for="lname">Last Name*</label>
<input type="text" name="lname" id="last_name"  value="<?php echo ($form_data===true? $formchecks[5]['lname'] : "");?>"/><br/>
<label for="email_address">Email Address*</label>
<input type="text" name="email" id="email" value="<?php echo ($form_data===true? $formchecks[5]['email'] : "");?>"/><br/>
<label for="zip_code">Zip</label>
<input type="text" name="zip_code" id="zip_code" value="<?php echo ($form_data===true? $formchecks[5]['zip_code'] : "");?>"/><br/>
<label for="street">Street Address</label>
<input type="text" name="street" id="street" value="<?php echo ($form_data===true? $formchecks[5]['street'] : "");?>"/><br/>
<label for="tel_no">Telephone Number*</label>
<input type="text" name="tel_no" id="tel_no" value="<?php echo ($form_data===true? $formchecks[5]['tel_no'] : "");?>"/><br/>
<label for="mobile">Mobile Number</label>
<input type="text" name="mobile" id="mobile" value="<?php echo ($form_data===true? $formchecks[5]['mobile'] : "");?>"/><br/>
<input type="submit" name="submit" value="submit"><br/>

    <?php

        ## this display the error as validated by the function.
        if ($formchecks[0]){
            foreach($formchecks[2] as $key => $formchecks[1]){
                if(array_key_exists($formchecks[1], $formchecks[3])){
                    echo $formchecks[3][$formchecks[1]]."<br/>";
                }
            }
        }
    ?>
</form>

  </body>
</html>

On success, if you want to show the user the summary of their submitted information, it can be access by calling $formchecks['locationInTheArray']['index_name']. Like......

$formchecks[5]['name'];

There might be some mistakes I made while typing codes above, please let me know I will be glad to correct them..

From what I see, you are concatenating $errors, but you didn't define the variable as string. Somewhere between lines 3 and 4 I would have made a $errors = '';

I also see that you ask again if the form was submited in line 14 after you asked in line 3. And for every if(isset($_POST['Submit'])) you open the curly braces but you forget to close them. Also you forgot to close the curly braces from line 16, 25 and 27. You seem to close them at lines 73-75 even though those are too far for your needs.

Member Avatar for diafol

Just to point out that you're sanitizing data not validating it. Your title says validate, but your code says sanitize. Granted you're checking for zero-length strings (zls), but that's as far as it goes. You could check postcode with a regex - there's a regex validator filter. You can also trim() the input data, as your code may escape validation if you're checking for zlses and a space character is present. Just a few thoughts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.