Validating and retaining form data using only php

I am writing an order system for my company with a strict spec from my boss. And I am not normally a programmer and fairly new to php. The spec includes a ban on the use of any javascript. I am having real difficulty writing the code to validate the data a user posts in a form to give their contact details etc. It is quite simple to do the validation itself but then how do I retain the posted data that is correct when the user needs to go back to correct mistakes? I have tried numerous ways, including using <?php echo $the_field_name ?> but that just means that the php code is echoed in the box to be completed! I just cannot retain the data already posted in the form. I have also tried php-form-validator and even the examples did not work!! Please can anyone help?

<?php echo $the_field_name ?> surely would help. Unless it written inside of PHP code itself.
If your form outputs using PHP echo, so, add this variable to the output string.

Also, if you make an example script, which contains only one field and only one validation routine, and post it here, it could help.
It is always better to test new tech in small example, and continue to real script only after this small example tested and worked all good. And you got undrestanding how it works.

You can do the validation and submitting on the same page.

for example first it will check if the form was filled


if(isset($_POST["contactName"]){
        //example of email validation
        $email = $_POST["email"];
	$pos = strpos($emai, "@");
	if ($pos === false) {
		print "Not Vaild";
	} else {
		print "Vaild";
	}
       //here you can do more validation or insert it into a database
}

That has to be at the top… so then you do an else statement for if the form was not filled out.


else{
echo
'<div id="login">
	<form action="this_page.php" method="post">
		Username:
		<br />
		<input type="text" name="contactName" class="textField"/>
		<br />
		Password:
		<br />
		<input type="password" name="email" class="textField"/>
		<br />
		<input type="submit/>
	</form>
</div>';
}

Good Luck!

An else doesn’t achieve what the OP wants. Instead of an else you want if the field wasn’t passed OR it is invalid then display the form. That’s where that echo statement inside the value field will allow the previously entered but invalid value to be displayed.


<input type="text" name="something" value="<?php if(isset($_POST['something'])) echo $_POST['something']; ?>">

Thank-you all for your help. I have used the code for a basic form that someone else got working and adapted it for a very short form to try myself - all the others I tried previously did not!
This is the form:

<?php

// Define error messages
define("errorCompany","You must give us a company or organisation name");
define("errorContactName","You must give us a contact name");
define("errorTelephone","Please enter your phone number. It must be at least 10 characters long.");
define("errorEmail","Invalid email address!");

function createForm($company="",$contact_name="",$telephone="",$email="",$error1="",$error2="",$error3="",$error4=""){
?>
<h2>Contact</h2><br />
<p>Please complete this form giving us your contact details. ALL fields are required</p>

      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <p><label>Company:</label><input type="text" name="company" class="textbox" value="<?php echo $company; ?>"></p>
        <div><?php echo $error1; ?></div>

        <p><label>Contact Name:</label><input type="text" name="contact_name" class="textbox" value="<?php echo $contact_name; ?>"></p>
        <div><?php echo $error2; ?></div>

        <p><label>Telephone:</label><input type="text" name="telephone" class="textbox" value="<?php echo $telephone; ?>"></p>
        <div><?php echo $error3; ?></div>

        <p><label>Email:</label><input type="text" name="email" class="textbox" value="<?php echo $email; ?>"></p>
        <div><?php echo $error4; ?></div>

        <p><input type="submit" name="submitBtn" value="Submit" class="submit"></p>
      </form>
<?php
}

// This function validates an email address
function isValidEmail($email){
   $pattern = "^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$";

   if (eregi($pattern, $email)){
      return true;
   }
   else {
      return false;
   }
}

?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<style type="text/css">
<!--
/* =Forms
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/	
#main label {
	font-size:11px;
	display: block;
	}
#main .submit input {
	margin-left: 0em;
	}
#main input {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 13px;
	color: #333;
	background: #f1f1f1;
	padding: 2px;
	border: 1px solid #999;
	width: 200px;
	}
#main .submit {
	color: #000;
	background: #ccc;
	border: 2px outset #d7b9c9;
	width: 100px;
	}
#main .error {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	color: ff0000;
	}	
.textbox {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 13px;
	color: #333;
	background: #f1f1f1;
	padding: 2px;
	border: 1px solid #999;
	width: 200px;
	}
.textbox-msg {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 13px;
	color: #333;
	background: #f1f1f1;
	padding: 2px;
	border: 1px solid #999;
	width: 400px;
	}

.button {
	color: #000;
	background: #ccc;
	border: 2px outset #d7b9c9;
	width: 100px;
	}
-->
</style>
</head>

<body>


<div id="wrap">
    <div id="main">
<?php if (!isset($_POST['submitBtn']))  {
    createForm();
} else  {
      $company = isset($_POST['company']) ? $_POST['company'] : "";
      $contact_name    = isset($_POST['contact_name'])    ? $_POST['contact_name'] : "";
      $telephone   = isset($_POST['telephone'])   ? $_POST['telephone'] : "";
	  $email   = isset($_POST['email'])   ? $_POST['email'] : "";

      $error  = false;
      $error1 = '';
      $error2 = '';
      $error3 = '';
	  $error4 = '';

      if (strlen($company)<1) {
          $error = true;
          $error1 = errorCompany;
      }
	  if (strlen($contact_name)<1) {
          $error = true;
          $error2 = errorContactName;
      }
	  if (strlen($telephone)<10) {
          $error = true;
          $error3 = errorTelephone;
      }
      if (!isValidEmail($email)) {
          $error = true;
          $error4 = errorEmail;
      }

      if ($error){
         createForm($company,$contact_name,$telephone,$email,$error1,$error2,$error3,$error4);
      }
      else {
//          want to send data to mysql database and send user to another page
    ?>
<p>Thank you for completing the form, now you can begin to make your order</p>
<?php
    }
}
?>
	</div>
</body>
</html>

But of course my form will be a lot more complicated than that. To take it in stages - firstly before arriving at this form the potentential customer will have entered their email address and a copied a captcha for security. If their email address is in the database they then receive a form with their contact details and are invited to make any changes (not my concern at present as that works fine). If they are not in the database they get a blank form to complete but the blank form must include the email address they have previously entered but which is editable - the code on the entry page checks that the email address is valid. I am obviously using sessions but after several attempts cannot see how to do this. Once the form is completed correctly I assume that I can, as the else, simply mysqlquery the data to a database? I haven’t tried that yet as I want to get the email bit correct. I also assume that I should be using htlmlspecialchars for security? Any help or comments will be greatly appreciated and then I can ask you about the more complicated bits of the form! Thank-you

What’she question at all?
without things that is not your concern.

The question was, as well as using the code I posted to validate form data and retain any data that is correct if there are errors to be corrected in the form but also how to include the previously entered email address in the new form (ie. as presented to the customer before he/she has added in any contact data). This email address comes from a previous form that allows the customr to enter the order system. Sorry if that was not clear but I was trying to explain what I wanted to do.
thankyou

it seems you have to set this existing email when calling createForm() function for the first time
createForm(“”,“”,“”,$email); instead of createForm();

In which form does email come to this script? POST, GET or session?

Well, in the old page that works apart from retaining posted data when it is validated, the email address and captcha from the login page were posted to this page, checked and then, assuming captcha is OK and email address is valid, the email address is:
$email = ($_POST[‘email’]);
then I do a search of the database for that email address and if it is not we come to the form I have been trying to do as above. So how do I define and include it in my contact form?
thanks again

Actually scrub that question - I figured it out myself. I define the email address just before the form i.e after the function createForm().
Next question to follow soon!
thanks again for your help

Following on from my previous posts as above I have the form validation working, apart from a couple of problems. I am using sessions
The code is as follows:

// Define error messages
define("errorCompany","You must give us a company or organisation name");
define("errorContactName","You must give us a contact name");
define("errorTelephone","Please enter your phone number. It must be at least 10 characters long.");
define("errorEmail","Invalid email address!");
define("errorAddress","Please enter an invoice address");
define("errorCountry","Please enter a country");
define("errorInvPostcode","Please enter a post/zip code");

function createForm($company="",$contact_name="",$telephone="",$email="",$inv_address="",$inv_country="",$inv_postcode="",$error1="",$error2="",$error3="",$error4="",$error5="",$error6="",$error7=""){
?>

<p>Please complete this form giving us your contact details. ALL fields are required</p>
<?php
$email = ($_SESSION['email']);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
      <table width="700" border="0" align="center" cellpadding="5" cellspacing="1" class="entryTable">
          	 <tr class="entryTableHeader">
            <td colspan="2">Contact Details</td>
        </tr>
        <tr>
            <td width="150" class= "label">Company:</td>
            <td class= "content"><input type="text" size="30px" name="company" id="company" value="<?php echo $company; ?>">
          <p class= "error"><?php echo $error1; ?></p></td>
           </tr>
			<tr>
            <td width="150" class= "label">Contact Name:</td>
            <td class= "content"><input type="text" size="40" name="contact_name" id="contact_name" value="<?php echo $contact_name; ?>">
                 <p class= "error"><?php echo $error2; ?></p></td>
            </tr>
 			<tr>
            <td width="150" class= "label">Telephone Number:</td>
            <td class= "content"><input type="text" size="30" name="telephone" id="telephone" value="<?php echo $telephone; ?>">
            <p class="error"><?php echo $error3; ?></p></td>
          <tr>
            <td width="150" class= "label">Email Address:</td>
            <td class= "content"><input type="text" size="40" name="email" id="email" value="<?php echo $email; ?>">
             <p class= "error"><?php echo $error4; ?></p></td></tr>
              <tr>
            <td width="150" class= "label">Invoice Address:</td>
            <td class= "content"><textarea name="inv_address" name="inv_address" cols="60" id="inv_address" value="<?php echo $inv_address; ?>"></textarea>
            <p class= "error"><?php echo $error5; ?></p></td>
            </tr>
            <tr>
            <td width="150" class= "label">Country:</td>
            <td class= "content"><input name="inv_country" type="text" id="inv_country" size="50" value="<?php echo $inv_country; ?>">
            <p class= "error"><?php echo $error6; ?></p></td>
            </tr>
            <tr>
            <td width="150" class= "label">Post/Zip Code:</td>
            <td class= "content"><input name="inv_postcode" type="text" id="inv_postcode" size="15" value="<?php echo $inv_postcode; ?>">
            <p class= "error"><?php echo $error7; ?></p></td>
            </tr>
            <tr>
            <td width="150" class= "label">Payment Type:</td>
            <td class= "content">Payment in Advance</td>
            </tr>
            <tr>
            <td width="150" class= "label">Terms & Conditions Signed?</td>
            <td class= "content">No</td>
            </tr>

        <tr><td></td><td><input type="submit" name="submitBtn" value="Submit" class="submit"></td></tr>
        </table></form>
<?php
}

// validates the email address
function isValidEmail($email){

   $pattern = ("/^[_\\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\\.)+[a-zA-Z]{2,6}$/i");

   if (preg_match($pattern, $email)){
      return true;
   }
   else {
      return false;
   }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link rel="stylesheet" type="text/css" href="include/newhunt.css" />
  <style type="text/css">
<!--
@import url("include/newhunt.css");
-->
</style>
<title>Contact Details</title>
</head>

<body>
 <div id = "container">
 <?php include ("include/header.php"); ?>
 <div id= "mainorder">
<?php if (!isset($_POST['submitBtn']))  {
    createForm();
} else  {
      $company = isset($_POST['company']) ? $_POST['company'] : "";
      $contact_name    = isset($_POST['contact_name'])    ? $_POST['contact_name'] : "";
      $telephone   = isset($_POST['telephone'])   ? $_POST['telephone'] : "";
	  $email   = isset($_POST['email'])   ? $_POST['email'] : "";
	  $inv_address   = isset($_POST['inv_address'])   ? $_POST['inv_address'] : "";
	  $inv_country   = isset($_POST['inv_country'])   ? $_POST['inv_country'] : "";
	  $inv_postcode = isset($_POST['inv_postcode'])   ? $_POST['inv_postcode'] : "";

      $error  = false;
      $error1 = '';
      $error2 = '';
      $error3 = '';
	  $error4 = '';
	  $error5 = '';
	  $error6 = '';
	  $error7 = '';

      if (strlen($company)<1) {
          $error = true;
          $error1 = errorCompany;
      }
	  if (strlen($contact_name)<1) {
          $error = true;
          $error2 = errorContactName;
      }
	  if (strlen($telephone)<10) {
          $error = true;
          $error3 = errorTelephone;
      }
      if (!isValidEmail($email)) {
          $error = true;
          $error4 = errorEmail;
      }
	  if (strlen($inv_address)<10) {
          $error = true;
          $error5 = errorAddress;
      }
	  if (strlen($inv_country)<1) {
          $error = true;
          $error6 = errorCountry;
      }
	  if (strlen($inv_postcode)<4) {
          $error = true;
          $error7 = errorInvPostcode;
      }

      if ($error){
         createForm($company,$contact_name,$telephone,$email,$inv_address,$inv_country,$inv_postcode,$error1,$error2,$error3,$error4,$error5,$error6,$error7);
      }
      else {

after this else the valid data is entered ito a mysql database. It all works very well EXCEPT that if there is an invalid field when the error messages come up all the valid data remains apart from the address - is this because it is a textarea and if so how do I fix it? The other problem is that because the email address is previously defined and comes from when the customer logs in and I want the previously validated email address to be reproduced in the form to be completed of course if there is a problem with other data when the form is completed then if the customer has changed the email address they want to use the previously defined email address appears. In most cases this won’t be a problem as the customer won’t want to change their email address but if they do is there a way I can get around this?

thanks for all your help

$email = ($_SESSION[‘email’]);
will solve your problem on any step.
just take it from session, not form

Thanks for the reply but I don’t understand where you mean me to place it, I am probably being very stupid. I have defined $email before the form. And that works fine for the first and any iterations of the form as long as the customer does not decide to change their email address from the one they logged in with because, if there is a mistake in that or any other field, when the error messages are given the email defaults to the original email address as of course it has already been defined in that session. It’s unlikely to be a major problem as most customers will not do this but I know that the odd one will and my boss will ask about this!! If all fields validate OK but the customer has changed the email address the new one is entered into the database so it’s only when the form has to be reproduced that this happens.

Using the code I posted above I can validate all fields and the correct data is retained when the error messages are given for invalid data, except for the address field. If I make this field input type=“text”, the data is reproduced but it just appears blank if it is in a <textarea>. I really need the address field to be a <textarea> so that the customer can see what they have written as text input just scrolls. Any ideas why textarea will not work?

Did you mean inv_address, not email address?
There is no value param for textarea. text must be placed between tags

<textarea name="inv_address" name="inv_address" cols="60" id="inv_address"><?php echo $inv_address; ?></textarea>

Yes, I did mean inv_address, sorry should have made that clear. I don’t understand what I should do to correct the problem. Do you mean that I can only have the data in a text input?

you have to replace the line starting from <textarea with one, I supplied above

Aah thanks! When I looked at the line you sent it looked at first glance the same as I already had - I should have looked more closely. And yes, that solves the problem thanks. Only thing is if you type in the address using the return key for new lines , the reproduced data in the form then has the carriage return and new line code in it e.g. this is the address\r
to send stuff to\r
so do it - how do I get rid of that?
You are really very helpful, sorry I keep coming back with new questions!

Seems very strange.
It shouldn’t be shown in the form.
Where do you see it? With invalid data error?

We are here to answer questions. So, better you feel sorry if you run out of questions :wink:
Also, I am trying to improve my english here, so, your wordy explanations are appreciated