Jump to content

posting a form that has errors then re-displaying that form with errors on page


Go to solution Solved by webdeveloper123,

Recommended Posts

Hi Guys,

I have a simple insert sql form in PDO which inserts the data just fine. Thing is I am now validating the data that goes into the database & this is the first proper time i've done it. At the moment I have only validated First Name field to be between 3-18 characters and that the user must agree to the T's & C's before that form data can be inserted into the database. What happens at the moment If I have less than 3 characters for the first name, when I press submit it goes to a new page, without the form there, but with the error message at the top of the page saying "First name has to be between 3-18 characters. Same kind of thing with T&C, it will take me to a new page without the form there and display error "You have to accept terms" etc

What I want to do is if there are errors on the form, when I press submit, I want the form to re-appear and then be able to put the error messages next to the html element it came from

I know this code isn't great but it's my first proper crack at PDO and validation.

<?php
declare(strict_types = 1);
 ?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Document </title>
</head>
<body>



<?php

include 'includes/db.php';
//include 'includes/functions.php';

$terms   = '';
$message = '';
$firstName = '';
$messageName = '';

function is_text($text, int $min = 0, int $max = 1000): bool
{
    $length = mb_strlen($text);
    return ($length >= $min and $length <= $max);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

  $sql = "INSERT INTO customer_details (first_name, last_name, address, town, county, post_code, fav_food, birthdate, email, terms) 
          VALUES (:first_name, :last_name, :address, :town, :county, :post_code, :fav_food, :birthdate, :email, :terms);";


$customers['first_name'] = $firstName = $_POST['fname'];
$customers['last_name'] = $lastName = $_POST['lname'];
$customers['address'] = $address = $_POST['address'];
$customers['town'] = $town = $_POST['town'];
$customers['county'] = $county = $_POST['county'];
$customers['post_code'] = $postCode = $_POST['postcode'];
$customers['fav_food'] = $favouriteFood = $_POST['fav_food'];
$customers['birthdate'] = $birthdate = $_POST['birthday'];
$customers['email'] = $email = $_POST['email'];
$customers['terms'] = $terms   = (isset($_POST['terms']) and $_POST['terms'] == true) ? true : false;
$message = $terms ? 'Thank you' : 'You must agree to the terms and conditions';

if ($terms  == false){
    echo $message;
    exit;

}

$valid = is_text($firstName, 3, 18);
    if ($valid) {
        $messageName = '';
    } else {
        $messageName = 'First Name must be 3-18 characters';

    }

    if ($valid == false){
      echo $messageName;
      exit;
    }



$statement = $pdo->prepare($sql);
$statement->execute($customers);




}

?>

<?= $message ?>
  <?= $messageName ?>


<form action="insert.php" method="post">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="<?= htmlspecialchars($firstName) ?>"><br>



  
  
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname"><br>
  
  <label for="address">Address</label><br>
  <input type="text" id="address" name="address"><br>

  
  <label for="town">Town</label><br>
  <input type="text" id="town" name="town"><br>
  
  <label for="county">County</label><br>
  <input type="text" id="county" name="county"><br>
  
  <label for="postcode">Post Code</label><br>
  <input type="text" id="postcode" name="postcode"><br><br>
  

  <label for="food">What is your favourite food?</label><br>
  <input type="radio" id="burger" name="fav_food" value="Burgers">
  <label for="burger">Burgers</label><br>
  <input type="radio" id="pizza" name="fav_food" value="Pizza">
  <label for="pizza">Pizza</label><br>
  <input type="radio" id="kebab" name="fav_food" value="Kebabs">
  <label for="kebab">Kebabs</label><br><br>
  
  
  <label for="birthday">Birthday:</label>
  <input type="date" id="birthday" name="birthday"><br><br>
  
  <label for="email">Email</label><br>
  <input type="text" id="email" name="email"><br><br>
  
  <input type="checkbox" id="terms" name="terms" value="true" <?= $terms ? 'checked' : '' ?>>
  <label for="terms">I agree to the terms.</label><br><br>

    <input type="submit" value="Submit">  
</form>



</body>
</html>

Thanks

I found a few ways such as:

 echo "<meta http-equiv='refresh' content='0'>";

   

or

header('Location: insert.php');

but none of them show me the error messages related to my validation

The trick is to write your form with php variables assigned to the value attibutes of your input tags.  When you process the submit button make sure you grab all of the POST values and assign them to these same variables.  That way if you have an error you simply resend the same form.

you mean do something like this?

$customers['first_name'] = $firstName = $_POST['fname'];

  <input type="text" id="fname" name="fname" value="<?= htmlspecialchars($firstName) ?>"><br>

 

Simple example

<?php

if ($_SERVER['REQUEST_METHOD']=='POST')  {
    $errors = [];
    
    $post = array_map('trim', $_POST);
    if ( strlen($post['name']) < 3 || strlen($post['name']) > 18 ) {
        $errors['name'] = 'Must be between 3 and 18 characters';
    }
    if (!isset($post['confirm'])) {
        $errors['confirm'] = 'Box must be checked';
    }
    
    if (!$errors) {
        // update database
        
        header("Refresh: 0");
        exit;
    }
}
?>
<!doctype html>
<html>
<head>
<title>Sample</title>
<style type="text/css">
    .errormsg {
        color : red;    
    }
</style>
</head>
<body>
    <form method='post'>
         Name 
         <input type='text' name='name' value='<?=$_POST['name'] ?? ''?>' >
         <br><span class='errormsg'><?=$errors['name'] ?? ''?></span>
         <br>
         <input type='checkbox' name='confirm' value='1'>
         Click this box
         <br><span class='errormsg'><?=$errors['confirm'] ?? ''?></span>
         <br>
         <input type='submit'>
    </form>
</body>
</html>

 

Hey Barand,

Yes that's pretty much what the new book I got shows how to do it, put the errors into an error array and then at the end see if there are any errors, then go from there. But I got some of the steps mixed up and ended up getting to where I got too.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.