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
prepared statementsby directly embedding variables in the sql statement rather than using placeholders to which you would bind the variablesuser_input()functions a lot of places, and like it is here, it's somewhat misunderstood and misused.