Separate form (html) and validation (php) with error messages

Right now, I use include to put my validation code into my main form page and use PHP_SELF. With this, the error messages I put in the validation logic shows at the form. However, I want to make my form action direct to the validation file and not use PHP_SELF. IF I do this, the script included in the form view which contains something like this “echo $firstnameErr” will get the error because $firstnameErr is defined in the validation file. Also, I want my validation file to go back to form view file if errors are committed (refill the input fields containing correct data, leave error fields blank), or redirect to the blank form if post is success. Actually, after validation, I insert sent values into database so Success Message will actually come after INSERT INTO DB.

Thank you for your responses. I am new here and struggling a bit. I have only studied HTML and CSS for two weeks and PHP for another two weeks so I still am not familiar with some techniques.``

HERE’S MY FORM CODE

<?php
include ('header.php');
require ('Validation.php');
?>
<!--THIS IS THE MAIN FORM-->
<div class="w3-round-large w3-container w3-margin w3-border w3-padding-8 w3-light-blue" style="position:relative;top:10px;">
<h2>CLCM Form</h2>
    <p><span class="error">* required field</p>
    <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST">
    First Name: <input type="text" name="firstname" class="w3-round"><span class="error"> * <?php echo $firstnameErr;?></span></input><br/><br/>
    Last Name: <input type="text" name="lastname" class="w3-round"><span class="error"> * <?php echo $lastnameErr;?></span><br/><br/>
    Gender:
    <input type="radio" name="gender" value="Male">Male
    <input type="radio" name="gender" value="Female">
        Female <span class="error">* <?php echo $genderErr;?></span><br/><br/>
    <input type="submit" value="Submit">
    <input type="reset" value="Reset">
    </form>
    <br/>
</div>

<?php

//DATABASE CONNECTION
include ('config.php');

//CODE FOR ADDING ENTRIES TO DATABASE
if ($firstname<>NULL) {
    $checkname="SELECT * FROM table1 WHERE FirstN='$firstname' AND LastN='$lastname'";
    $cname=$conn->query($checkname);
    $rcname=$cname->fetch_assoc();
    if (empty($rcname)) {
        $sql = "INSERT INTO table1 (FirstN, LastN, Gndr) VALUES ('$firstname','$lastname','$gender')";
    if ($conn->query($sql) === TRUE) {
        echo '<div>Entries successfully added!</div>';
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    } else {
        echo "Person already exists in Database";
    }
}
$conn->close();
?>

<?php
include ('footer.php');
?>

AND MY VALIDATION

<?php
/*Here starts the PHP Form Code. It starts with defining the input variables as NULL
because their new values will depend upon the user's input. They're placed at the beginning
so that all required variables are quickly defined*/

$firstname=$lastname=$gender=null;
$firstnameErr=$lastnameErr=$genderErr=null;

/*We need to make sure that the method used is POST for security*/

if ($_SERVER['REQUEST_METHOD']=="POST"){    /*if POST is true, form is submitted, continue to if-else*/
    if (empty($_POST["firstname"])){             /*if empty there's error, else continue*/
        $firstnameErr="First Name is Required";        
    } else {
        $firstname=test_input($_POST["firstname"]);          
        if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {  /*this tests if name contains valid characters only*/
        $firstnameErr = "Only letters and white space allowed";
                                         /*name is null if there's error*/
        }
    }
    if (empty($_POST["lastname"])){             /*if empty there's error, else continue*/
        $lastnameErr="Last Name is Required";        
    } else {
        $lastname=test_input($_POST["lastname"]);          
        if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {  /*this tests if name contains valid characters only*/
        $lastnameErr = "Only letters and white space allowed";
                                         /*name is null if there's error*/
        }
    }
   
    if (empty($_POST["gender"])){               /*if empty gender has error, else continue*/
        $genderErr="Gender is required";
    } else {
        $gender=test_input($_POST["gender"]);
    }
}

function test_input ($data){        /*this removes backslashes, space at beginning and end, special*/
    $data=trim($data);              /*characters*/
    $data=stripslashes($data);      /*$data is any */
    $data=htmlspecialchars($data);
    return $data;
}

/*If even one error exists, no output is shown*/

if (empty($_POST["gender"])||empty($_POST["firstname"])||empty($_POST["lastname"])) {
    $firstname=$lastname=$gender=null;
} else {
        if (!preg_match("/^[a-zA-Z ]*$/",$firstname)||!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
            $firstname=$lastname=$gender=null;
        }
    }

?>

Welcome to SitePoint Forums, @exztinct01. It will be easier to read your code if you highlight the code, then select the </> icon at the top of the edit screen for format the code. Or you could just place three backticks (`) on the line before the code and three backticks on the line after the code.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.