How can i use custom function to validate post data in php - php

I want to validate my form post using function and then insert it into database.
I have been able to do that without putting it into function but when i put it into a function it inserts without validating the input fields.
Thanks ;)
Here is my code:
<?php
function validate_post(){
global $link;
if (isset($_POST['submit'])) {
$error = array();
if (!isset($_POST['cat_title']) || empty($_POST['cat_title'])) {
$error[] = "field cannot be empty";
} else {
//check if a name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $_POST['cat_title'])) {
$cat_err = "Only letters and whitespace allowed";
}
}
//if no errors found
if (empty($error) && empty($cat_err)) {
$cat_title = htmlentities($_POST['cat_title']);
$sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
$insert = mysqli_query($link, $sql);
confirm_query($insert);
if (mysqli_affected_rows($link) == 1) {
$post_info = "Category has been added";
redirect("categories.php");
} else {
$post_info = "Adding category failed";
}
} else {
$post_info = "Field cannot be empty";
}
}
}
?>
<?php validate_post(); ?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
<?php
if(isset($post_info))echo $post_info."<br>";
if(isset($cat_err))echo $cat_err."\n" ?>
<div class="form-group">
<label for="cat_tile">Categories</label>
<input type="text" class="form-control" name="cat_title" id="cat_tile"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="+ Add Category" name="submit" >
</div>
</form>

You can pass your post data by reference to a function like this:
function checkFormValue(&$inputData) {
if (isset($inputData) && !empty($inputData)) {
return $inputData;
}
return "";
}
Call this function on $_POST data to validate it:
$catTitle = checkFormValue($_POST["cat_title"]);
var_dump($catTitle);
If it fails to validate than it will return empty string. Using this function you can check isset and for !empty many of your form fields.

below code will help you ..
<?php
function validate_post(){
global $link;
if (isset($_POST['submit'])) {
$cat_err = "";
if (!isset($_POST['cat_title']) || empty($_POST['cat_title']) || $_POST['cat_title']=="") {
$cat_err = "field cannot be empty";
} else {
//check if a name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $_POST['cat_title'])) {
$cat_err = "Only letters and whitespace allowed";
}
}
//if no errors found
if ($cat_err=="") {
$cat_title = htmlentities($_POST['cat_title']);
$sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
$insert = mysqli_query($link, $sql);
confirm_query($insert);
if (mysqli_affected_rows($link) == 1) {
$cat_err = "Category has been added";
redirect("categories.php");
} else {
$cat_err = "Adding category failed";
}
} else {
$cat_err = "Field cannot be empty";
}
return $cat_err;
}
}
?>
<?php $data=validate_post();echo $data;?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
<div class="form-group">
<label for="cat_tile">Categories</label>
<input type="text" class="form-control" name="cat_title" id="cat_tile"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="+ Add Category" name="submit" >
</div>
</form>

Your function doesn't return any information. You need to tell it to return the errors, and then do something with them. You need to restructure the way messages are organized in your function, but the gist is this:
add return $error; to the end of your validate function.
Then in your page body:
<?php $errors = validate_post(); ?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
<?php
foreach($errors as $error)
{
echo $error;
}
?>
<div class="form-group">
So, change your validate function to save all messages into a single array, return the array, then process the items.
Variables declared inside a function only "exist" within the scope of that function. $post_info inside your function has no relationship to $post_info outside the function.

Try to pass in the $_POST array:
if (isset($_POST['submit'])){
validate_post($_POST)
}
function validate_post($post_array) {
// your code here
}
Matt first suggested this, but here is how you would do that.

Using your code this is the rundown to what you need to do for the function.
<?php
function validate_post($link, $data=[]) {
$error = array();
if (!isset($data['cat_title']) || empty($data['cat_title'])) {
$error[] = "field cannot be empty";
} else {
//check if a name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $data['cat_title'])) {
$cat_err = "Only letters and whitespace allowed";
}
}
//if no errors found
if (empty($error) && empty($cat_err)) {
$cat_title = htmlentities($data['cat_title']);
$sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
$insert = mysqli_query($link, $sql);
confirm_query($insert); //This is another function you created???
if (mysqli_affected_rows($link) == 1) {
$post_info = "Category has been added";
redirect("categories.php");
} else {
$post_info = "Adding category failed";
}
} else {
$post_info = "Field cannot be empty";
}
}
if (isset($_POST['submit'])) {
include 'dbfile.php'; // Containing your db link variable if that is how you've done it
validate_post($link, $_POST); // Usually you need to pass your database link by reference also rather than by global.
}
?>
--html section--

Related

php login form display errors from array

I'm having some trouble displaying my errors on this login form.
The login works but I can't figure out how to display those errors.
I just need to display them between the login field and the footer. I suppose the problem should be the last part of the foreach that should go true the error array.
<!DOCTYPE html>
<html lang="en">
<body>
<?php
include ('includes/header.php');
?>
<div class="nav">
<?php
include ('includes/menu.php');
$error= logInData();
?>
</div>
<section role="main">
<div class="logIn">
<h3>Intranet Login</h3>
</div>
<form action="" method="post">
<fieldset>
<legend>Student Log in</legend>
<div>
<label for="username">Enter username: </label>
<input type='text' id="userN" name="userN" value = "<?php if (isset($error['usern'])){echo $error['usern'];} ?>">
</div>
<div>
<label for="password">Enter password: </label>
<input type='password' id="pass" name="pass" value = "">
</div>
<div>
<p class="red"><?php if (isset($error['both'])) {
echo $error['both'];
} ?></p>
</div>
<div>
<input type="submit" name="submit" value="Log-In">
</div>
</fieldset>
</form>
</section>
<?php
function logInData (){
$error = array();
$validated = array();
$clean = array();
$pass = false;
if (isset($_POST['submit']) && $pass == true) {
$inputPass = ($_POST['pass']);
$trimPass = trim($inputPass);
$inputUsern = ($_POST['userN']);
$trimUsern = trim($inputUsern);
if(!empty($trimPass)){
if (!ctype_alpha($trimPass)) {
$error['passw'] = 'No special characters allowed on password';
$pass = false;
}else{
if(empty($trimPass)){
$error['passw'] = 'password field empty';
$pass = false;
}else{
$clean['passw'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
if(!empty($trimUsern)){
if (!ctype_alpha($trimUsern)) {
$error['userN'] = 'No special characters allowed on username';
$pass = false;
}else{
if(empty($trimPass)){
$error['userN'] = 'username field empty';
$pass = false;
}else{
$clean['userN'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
$dir = '/home/sbau01/public_www/php/fma/data';
if (is_dir($dir)){
$handleDir = opendir('/home/sbau01/public_www/php/fma/data');
$path = "/home/sbau01/public_www/php/fma/data/data.txt";
if(is_file($path)){
$handle = fopen($path, 'r');
while(!feof($handle)){
$dataRow = fgets($handle);
if(!empty($dataRow)){
$separate = explode(' ',$dataRow);
$storedUsern = trim($separate[3]);
$storedPassword = trim($separate[4]);;
if (($clean['userN'] == $storedUsern) && ($clean['passw'] && $storedPassword)){
$match = true;
header('location: intranet.php');
}else{
$error['match']='<span >Username/Password is incorrect!!</span>';
$pass = false;
}
}
}fclose($handle);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}closedir($HandleDir);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}
}else {
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
}
}
?>
<footer>
<?php include ('includes/footer.php');?>
</footer>
</body>
</html>
Its a simple brackets error:
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
The part above is in the else condition of if (isset($_POST['submit']) && $pass == true) {
Thats why this will never execute. Simply remove the bracket above this part and add it after the foreach.
Saving Passwords in text files is NOT a great idea!
In line 101 you have probably an little mistake:
You just check if there are the variables, you dont check if they are equal ($clean['passw'] && $storedPassword)){
A couple of issues identified.
Do you have display errors turned on? https://stackoverflow.com/a/21429652/1246494
You are calling $error= logInData(); at the top, but have your function logInData() { ... } created down below.
I think what you want to do it put the whole function in an include file at the top like:
include ('includes/header.php');
include ('includes/logInFunction.php');
You then want to call logInData(); down in the body.
Another issue is your function puts data in an array and echos data. If you are going to have $error= logInData(); at the top of your page try moving this out of your function and into your body where you want to output the errors.
if(count($error) > 0)
{
foreach($error as $key => $value)
{
echo "ERROR: $value<br />\n";
}
}

Html not send post data to php

I don't know why my html form is not sending data. I have 3 file called default.php, prosesbacasoal.php and bacasoal.php. Because the default.php is too long I just write the html form I get from inspect element
<form method="post" action="prosesbacasoal.php"><div class="head-main- recenttest-result">
<input type="hidden" name="nomor" value="2">
<button class="head-main-recenttest-result-wait" style="text-decoration:none;" type="submit" name="submit">2.Soal Kedua</button> </div></form>
prosesbacasoal.php
<?php
session_start();
if(isset($_POST['submit'])) {
if(isset($_POST['nomor'])) {
$_SESSION['submitsoal'] = true;
$_SESSION['nomorsoal'] = $_POST['nomor'];
header("Location:bacasoal.php");
exit;
} else {
header("Location:bacasoal.php");
exit;
}
} else {
header("Location:bacasoal.php");
exit;
}
?>
Also the bacasoal.php is too long so I just write the part of it:
<?php
session_start();
if(isset($_SESSION['submitsoal'])) {
if(isset($_SESSION['nomorsoal'])) {
$nomorsoal = $_SESSION['nomorsoal'];
$queryjudulnya = "SELECT nomorsoal,judul,soal FROM soal WHERE nomorsoal='".$nomorsoal."'";
$runqueryjudulnya = mysqli_query($konek,$queryjudulnya);
$countqueryjudulnya = mysqli_num_rows($runqueryjudulnya);
if($countqueryjudulnya != 0) {
$assocqueryjudulnya = mysqli_fetch_assoc($runqueryjudulnya);
$juduldatabase = mysqli_real_escape_string($assocqueryjudulnya['judul']);
$soaldatabase = mysqli_real_escape_string($assocqueryjudulnya['soal']);
$nomorsoaldatabase = mysqli_real_escape_string($assocqueryjudulnya['nomorsoal']);
} else {}
} else {}
} else {}
?>
<?php
if(isset($juduldatabase) && isset($nomorsoaldatabase)) {
echo "<div class=\"head-main-recent\"> ".$nomorsoaldatabase.$juduldatabase." </div>";
} else {
echo "<div class=\"head-main-recent\">Judul soal tidak ditemukan!</div>";
}
?>
bacasoal.php keep echo the fail statement "Judul soal tidak ditemukan!"
Does anyone know why? (live demo : http://english-lesson.16mb.com/)
You can do it like below so that if error is there then it will display or any how at-least some useful information will display:-
default.php:-
<form method="post" action="prosesbacasoal.php">
<div class="head-main-recenttest-result">
<input type="hidden" name="nomor" value="2">
<button class="head-main-recenttest-result-wait" style="text-decoration:none;" type="submit" name="submit">2.Soal Kedua</button>
</div>
</form>
prosesbacasoal.php:-
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
if(isset($_POST['nomor'])) {
$_SESSION['submitsoal'] = 'true';
$_SESSION['nomorsoal'] = $_POST['nomor'];
header("location:bacasoal.php");
exit;
} else {
header("location:default.php");
exit;
}
?>
bacasoal.php:-
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$juduldatabase = '';
$soaldatabase = '';
$nomorsoaldatabase = '';
if(isset($_SESSION['submitsoal']) && isset($_SESSION['nomorsoal'])) {
$nomorsoal = $_SESSION['nomorsoal'];
$queryjudulnya = "SELECT nomorsoal,judul,soal FROM soal WHERE nomorsoal='".$nomorsoal."'";
echo $queryjudulnya;
$runqueryjudulnya = mysqli_query($konek,$queryjudulnya);
if($runqueryjudulnya){
$countqueryjudulnya = mysqli_num_rows($runqueryjudulnya);
if($countqueryjudulnya > 0) {
while($assocqueryjudulnya = mysqli_fetch_assoc($runqueryjudulnya)){
$juduldatabase = $assocqueryjudulnya['judul'];
$soaldatabase = $assocqueryjudulnya['soal'];
$nomorsoaldatabase = $assocqueryjudulnya['nomorsoal'];
}
} else {
echo "No matching record found";
}
}else{
echo "Query execution failed because of:-".mysqli_error($konek);
}
}else {
echo "Session variables are not set";
}
?>
<?php
if(isset($juduldatabase) && isset($nomorsoaldatabase)) {
echo "<div class="head-main-recent"> ".$nomorsoaldatabase.$juduldatabase."</div>";
} else {
echo "<div class="head-main-recent">Judul soal tidak ditemukan!</div>";
}
?>
Note:- if still no error and no records,then echo query and run that query manually in db and check any record are coming or not?
In 3rd line of your HTML code I can see </div> before form tag ending. I cant see dive start tag after form tag
<button class="head-main-recenttest-result-wait" style="text-decoration:none;" type="submit" name="submit">2.Soal Kedua</button> </div></form>
Replace by
<button class="head-main-recenttest-result-wait" style="text-decoration:none;" type="submit" name="submit">2.Soal Kedua</button></form>
it was php session problem , fixed it after i session_destroy(); it using logout.php

PHP Variable not storing value after submit

I have a simple PHP page, and am attempting to validate form input.
Upon hitting submit with invalid data, the inputted value is not being returned in my echo statement
I want to echo the input as the value so that the user can understand what they typed wrong. Below is my code;
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
<?php
// define variables and set to empty values
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<!--Begin HTML Form-->
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr;?></span><br> <!--<p class='spacerLine'></p>-->
<input type="text" class="largeInput" name="contactFirstName" value="<?php echo $contactFirstName;?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php echo $contactEmail;?>">
<br><br>
<?php echo "TEST" . $contactEmail;?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php echo $retailerID;?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Any thoughts? I'm new to PHP but have been following the W3 tutorial pretty tightly. Could it be my classes throwing things off? Or did I just mess up a variable name?
Thanks for all help
I want to echo the input as the value so that the user can understand what they typed wrong.
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
First of all, echo $_POST values instead of $contactFirstName, $contactEmail etc. because these values are available only after it crosses all the validation steps.
Second, there's no function named test_input() in your code, or may be it is defined somewhere else.
And finally, look at this statement here:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { ..
There's no variable named $email in your code. It should be:
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) { ..
So your code should be like this:
<?php
function test_input($string){
// your code
}
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr; ?></span><br>
<input type="text" class="largeInput" name="contactFirstName" value="<?php if(isset($_POST['contactFirstName'])){ echo $_POST['contactFirstName']; } ?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; } ?>">
<br><br>
<?php
echo "TEST ";
if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; }
?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php if(isset($_POST['retailerID'])){ echo $_POST['retailerID']; } ?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Here's the reference for isset() function:
isset()
Sidenote: Even though this answer will work you temporarily, but you should definitely look at how to strictly validate form inputs using regex.
The below line validates the value of the variable $email, but i can't see anywhere in your code where does that variable get set a value, that can be the first step in fixing the issue.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
You are not defining test_input() function and $email is not defined in this line:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
This code works for me so far:
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = $_POST["contactFirstName"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = $_POST["contactEmail"];
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = $_POST["retailerID"];
}
}

How to keep form data after validation fail and when the page redirects with PHP?

I have this form that I'm working with off a tutorial. I'm trying keep the fields populated when there is a validation error.
Here is my form:
<div class="add">
<?php $errors4 = errors_seesion_funtion(); ?>
<?php echo form_errors($errors4); ?>
<div class="error-message"><?php echo message(); ?></div>
<div class="done"><input name="Done" type="button" value="Done" /></div>
<h2>ADD New Department:</h2>
<form action="create-department-process.php" method="post">
<p class="department-name">Department name:
<input type="text" name="department_name" id="department-name" value="<?php if (isset($_POST['department_name'])) { echo htmlentities($_POST['department_name']); } ?>" />
<span class="error">* <?php if (!empty($errors4)) { echo "<div class=\"error\">";
echo "Hi";
echo "</div>";
}
?></span>
</p>
<p class="department-name">Test name:
<input type="text" name="test_name" id="test-name" value="" />
<span class="error">* <?php /*echo form_errors($errors4); */
if (!empty($errors4)) {
echo "<div class=\"error\">";
echo "test name";
echo "</div>";
}
?></span>
</p>
<input type="submit" name="dept_added" id="add-btn" value="ADD Department" />
</form>
<br />
<div class="cancel">Cancel</div>
Here is my Session:
session_start();
function message() {
if (isset($_SESSION["message"])) {
$output = "<div class='message'>";
$output .= htmlentities($_SESSION["message"]);
$output .= "</div>";
// clear message after use
$_SESSION["message"] = null;
return $output;
}
}
function errors_seesion_funtion() {
if (isset($_SESSION["errors3"])) {
$errors2 = $_SESSION["errors3"];
$_SESSION['post_data'] = $_POST;
// clear message after use
$_SESSION["errors3"] = null;
return $errors2;
}
}
Here is my Validation Functions:
$errors_array = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors6;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors6[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Here is my create-department-process.php
if (isset($_POST['dept_added'])) {
$department_name = mysql_prep($_POST["department_name"]);
//Validations for form
$required_fields = array("department_name", "test_name");
validate_presences($required_fields);
if (!empty($errors6)) {
$_SESSION["errors3"] = $errors6;
redirect_to("add-department.php"); //this is the page the form is on
}
// Process the form
$query1 = "INSERT INTO departments (";
$query1 .= " department_name ";
$query1 .= ") VALUES ( ";
$query1 .= " '{$department_name}' ";
$query1 .= ") ";
$result1 = mysqli_query($db_connection, $query1);
if ($result1) {
// Success
$_SESSION["message"] = "Department created.";
redirect_to("add-department.php");
} else {
// Failure
$_SESSION["message"] = "Department creation failed.";
redirect_to("creation-error.php");
}
} else {
redirect_to("fail.php");
}
I've tried to put this in the value of my form
<?php if (isset($_POST['department_name'])) { echo htmlentities($_POST['department_name']); } ?>
But the value I type in doesn't stay when PHP runs the form validation and redirects. Does anyone have any idea on how I can keep the data I type into the form fields when I have a validation error?
Thank you for your time and Help! I really appreciate it!
I think your POST data is getting lost when you do this:
if (!empty($errors6)) {
$_SESSION["errors3"] = $errors6;
redirect_to("add-department.php"); //this is the page the form is on
}
I'm guessing redirect_to actually redirects your browser to the specified page, therefore resetting the REQUEST values and losing the pervious POST data. You either need to save the POST values in the session (a la errors_seesion_funtion) and access them from there in your form, or include the form above to preserve the original POST values.

Strange validation error for form

The error i got was:
Notice: Undefined index: visible in C:\xampp\htdocs\introducingphp\includes\validation_function.php on line 22
It should not happen since i already instantiated all the variables including visible
Validation_function.php
<?php
$errors = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
// * presence
// use trim() so empty spaces don't count
// use === to avoid false positives
// empty() would consider "0" to be empty
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
// * string length
// max length
function has_max_length($value, $max) {
return strlen($value) <= $max;
}
function validate_max_lengths($fields_with_max_lengths) {
global $errors;
// Expects an assoc. array
foreach($fields_with_max_lengths as $field => $max) {
$value = trim($_POST[$field]);
if (!has_max_length($value, $max)) {
$errors[$field] = fieldname_as_text($field) . " is too long";
}
}
}
// * inclusion in a set
function has_inclusion_in($value, $set) {
return in_array($value, $set);
}
?>
new_page.php (the page that has the one-page submit form that does validation)
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
// Can't add a new page unless there is a subject as a parent
if (!$current_subject) {
// subject ID was missing or invalid or
//subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("menu_name", "position", "visible",
"content");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 60);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// perform Create
//add the subject_id
$subject_id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//escape content
$content = mysql_prep($_POST["content"]);
// 2. Perform database query
$query .= "INSERT INTO pages (";
$query .= " subject_id, menu_name, position, visible,
content";
$query .= ") VALUES (";
$query .= " {$subject_id}, '{$menu_name}', {$position},
{$visible}, '{$content}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Page Created.";
redirect_to("manage_content.php?subject=" .
urlencode($current_subject["id"]));
}else {
// Failure
$_SESSION["message"] = "Page creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<?php include("header.php"); ?>
<div id="main">
<div id="navigation">
<?php echo navigation($current_subject, $current_page); ?>
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Page</h2>
<form action="new_page.php?subject=<?php echo
urlencode($current_subject["id"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$page_set =
find_all_pages_for_subject($current_subject["id"], false);
$page_count = mysqli_num_rows($page_set);
for($count=1; $count <= ($page_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible
<input type="radio" name="visible" value="0" /> NO
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea name="content" rows="20" cols="80"></textarea>
</p>
<input type="submit" name="submit" value="Create Page" />
</form>
<br />
<a href="manage_content.php?subject=<?php echo
urlencode($current_subject["id"]); ?>">Cancel</a>
</div>
</div>
<?php include("includes/footer.php"); ?>
You probably have a typo on the input HTML field. You can use:
if (isset($_POST[$field])) {
on validate_presences() function to be sure that the value exists.
When you try to do trim($_POST[$field]); you assume, the field exists in the $_POST array - for visible it does not in this case. You could move the trim to has_presence()
function has_presence($value) {
return isset($value) && trim($value) !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Now when you will only have the trim if the variable exists.
Okay, marking the radio check button makes it work now. Thanks for all your inputs guys. It has helped me a great deal.

Categories