Short version:
I have already thought of a couple ways of answering my own question, but they aren't the most elegant solutions out there.
My current thought process is: save all of their inputted data as $_SESSION variables -- and whenever they load the form, do an if
statement around each input, as such;
if(isset($_SESSION['foo_data'])) {
echo "<input type='text' name='foo' value='$_SESSION["foo_data"]'>";
} else {
echo "<input type='text' name='foo' placeholder='Enter your text here...'>";
}
This method will work, but it also involves an immensely tedious definition of 140+ session variables, followed by an even more tedious and immense creating if/else statements around EVERY form field.
Is there any better way to do this?
Additional info: using plain php, no frameworks of any kind.
Sessions are unnecessary. Your basic plan should be:
Before I started using CodeIgniter, I used to use if
statements to validate and generate error messages like this:
if ( ! empty($_POST['email'])){
if ($this->verifyInput($_POST['email'], 6)){
$fill['email'] = $_POST['email'];//$fill is the array of values that passed validation
} else $tally++;//$tally keeps a running count of the total number of erors
}
I make a function call to $this->verifyInput
which accepts the field value and the type of validation to perform--in this case it's 6, which indicates email. Here's my validation function:
function verifyInput($input, $type){
if ($type == 0) $pattern = '/^1$/';//just the number 1
elseif ($type == 1) $pattern = '/^[0-9]+$/';//just integers
elseif ($type == 2) $pattern = '/^[A-Za-zÁ-Úá-úàÀÜü]+$/';//just letters
elseif ($type == 3) $pattern = '/^[0-9A-Za-zÁ-Úá-úàÀÜü]+$/';//integers & letters
elseif ($type == 4) $pattern = '/^[A-Za-zÁ-Úá-ú0-9àÀÜü\s()\/\'":\*,.;\-!?&#$@]{1,1500}$/';//text
elseif ($type == 5) $pattern = '/^[A-Za-zÁ-Úá-úàÀÜü0-9\']+[A-Za-zÁ-Úá-úàÀÜü0-9 \'\-\.]+$/';//name
elseif ($type == 6) $pattern = '/^.+@[^\.].*\.[a-z]{2,}$/';//e-mail
elseif ($type == 7) $pattern = '/^((\(0?[1-9][0-9]\))|(0?[1-9][0-9]))?[ -.]?([1-9][0-9]{3})[ -.]?([0-9]{4})$/';//brazilian phone
if (preg_match($pattern, $input) == 1) return true;
else return false;
}
Once the validation is done, I use the $fill
array to prefill the form for each field:
<input class="field" type="text" name="email" value = "<?php echo $fill['email']; ?>"/>
You should also make sure that $fill
is iniciated with empty values such as $fill['email']='';
or check to make sure the values are set before filling the input tags:
<input class="field" type="text" name="email" value = "<?php if(isset($fill['email'])) echo $fill['email']; ?>"/>
These are just general guidelines that you can adapt to your needs, but I found this to be a convenient way to handle it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With