0

I'm new to PHP and I'm trying some form validation. I have the following code:

I submit a form and submit the data to an SQL statement if it passes validation. If the form is valid, it redirects to an external success page.

What I can't do is get the original post variables onto the success page. How could I do this please? My code is below:

PHP:

   <body>
<?php

$firstnameErr = $emailErr = $lastnameErr = $gradeErr = $roleErr = "";
$firstname = $email = $lastname = $grade = $role = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["firstname"])) {
        $firstnameErr = "First name is required";
    } else {
        $firstname = user_input($_POST["firstname"]);
    }

    if (empty($_POST["lastname"])) {
        $lastnameErr = "Last mame is required";
    } else {
        $lastname = user_input($_POST["lastname"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = user_input($_POST["email"]);
    }

    if (empty($_POST["grade"])) {
        $gradeErr = "Grade is required";
    } else {
        $grade = user_input($_POST["grade"]);
    }


    if (empty($_POST["role"])) {
        $roleErr = "Role is required";
    } else {
        $role = user_input($_POST["role"]);
    }

    if($firstnameErr == '' && $emailErr == '' && $lastnameErr == '' && $gradeErr == '' && $roleErr == ''){

        $stmt = $conn->prepare("INSERT INTO `Tom`.`staff_details` (`first_name`, `surname`, `role`, `grade`,`email`) VALUES ('$firstname', '$lastname','$role', '$grade','$email');");
        $stmt->execute();
        header('Location: staff_added.php');
        exit();
    };

}

function user_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>

HTML:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <fieldset>
        <p><span class="error">* required field</span></p>
        <label>First name:</label><input type="text" name="firstname" />
        <span class="error">* <?php echo $firstnameErr;?></span><br>
        <label>Last name:</label><input type="text" name="lastname" />
        <span class="error">* <?php echo $lastnameErr;?></span><br>
        <label>Role:</label><input type="text" name="role" />
        <span class="error">* <?php echo $roleErr;?></span><br>
        <label>Grade:</label><input type="text" name="grade" />
        <span class="error">* <?php echo $gradeErr;?></span><br>
        <label>Email:</label><input type="text" name="email" />
        <span class="error">* <?php echo $emailErr;?></span><br><br>
        <input class="standard_submit" type="submit" value="Save" id="submit_search_button">
    </fieldset>

</form>

I would like those variables to move across to the staff_added.php page so that I can print them back to the user. I've done some reading over this but as far, it's not making much sense.

Any help would be appreciated.

Thank you

4
  • You need to either store some of the info in a session, or store the users ID and load the data from your db on the success page. - There are multiple ways of doing it, these are just a couple of them. Commented Jun 19, 2017 at 9:21
  • 1
    You are entirely missing the point of prepared statements by directly embedding variables in the sql statement rather than using placeholders to which you would bind the variables Commented Jun 19, 2017 at 9:23
  • I see those user_input() functions a lot of places, and like it is here, it's somewhat misunderstood and misused. Commented Jun 19, 2017 at 9:25
  • I've seen an online example within W3schools to get me started but the explanation there is pretty vague. The prepared statements will come next when I start refactoring with more understanding, I'm just going one step at a time. Commented Jun 19, 2017 at 9:27

2 Answers 2

1

You can store the variables in a SESSION object and then will be available from everywhere :

<?php
session_start();
//other code...
$_SESSION["role"] = $role; 
//other code...
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Would I need to declare the end of the session in the confirmation page?
You should use session_destroy() , in your case i think you shouldn't call it in your page , read here
You could use $_SESSION[ 'formdata' ]=$_POST and then access the elements using $_SESSION[ 'formdata' ]['role'] etc rather than individual session variables
1

Using prepared statements you should be looking at an approach like this perhaps rather than directly embedding variables in the sql.

<?php
    function user_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    $firstname = $email = $lastname = $grade = $role = false;

    if( $_SERVER["REQUEST_METHOD"] == "POST" ) {
        $errors=array();


        if( empty($_POST["firstname"])) $errors[] = "First name is required";
        else $firstname = user_input( $_POST["firstname"] );


        if( empty($_POST["lastname"])) $errors[] = "Last mame is required";
        else $lastname = user_input($_POST["lastname"]);


        if( empty($_POST["email"])) $errors[] = "Email is required";
        else $email = user_input($_POST["email"]);


        if( empty($_POST["grade"]) ) $errors[] = "Grade is required";
        else $grade = user_input($_POST["grade"]);



        if( empty($_POST["role"])) $errors[] = "Role is required";
        else $role = user_input( $_POST["role"] );


        if( empty( $errors ) ){

            $stmt = $conn->prepare("INSERT INTO `Tom`.`staff_details` (`first_name`, `surname`, `role`, `grade`,`email`) VALUES (?,?,?,?,?);");
            if( $stmt ){
                $stmt->bind_param('sssss',$firstname,$lastname,$role,$grade,$email);
                $stmt->execute();

                exit( header( 'Location: staff_added.php' ) );
            } else { echo 'statement failed'; }


        } else {
            foreach( $errors as $error )echo $error . '<br />';
        }

    }
?>

3 Comments

I'm getting an error when applying this code. My connection uses PDO and it tells me that bind_params is an undefined method for PDO
I found bindParam which worked. Thank for the help with prepared statements
Sorry - my mistake ~ I thought you were using mysqli rather than PDO

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.