Is it better to send an html form to a seperate page, or send it back to the same page??
i keep hearing to seperate logic from presentation, so I was wondering if I should seperate my forms from my form handlers as well.
As of now, Im doing this...
<?php
if(isset($_POST['submitted'])){
//Validate the form
if(empty($_POST['name'])){
$errors['name'] = 'Please enter your name';
}
//IF no errors INSERT INTO database and redirect
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="name" value="<?php if(isset($_POST['name'])) echo $_POST['name']; ?>" />
<?php if(isset($errors['name'])) echo '<span class="error">'.$errors['name'].'</span>'; ?>
<input type="submit" />
</form>
Is this good, or should I completely seperate the php from the form and just include one into the other... or something of the sort
I actually find having the submission processing logic in a separate file that would be included (in my class a class) allows you to keep your logic away from the presentation, but have the errors of validation/etc appear directly on your form where you expect them to. A small example of what I propose:
<?php // form.php
$form = array(
"test"=>"default value",
);
$errors = array();
if (count($_POST)) {
include "form.process.php";
}
if (count($errors)) {
echo "<ul class='errors'>";
foreach ($errors as $error) {
echo "<li>".htmlentities($error)."</li>";
}
echo "</ul>";
}
?>
<form method="POST"> <!-- no action means submit to the same page you are on -->
<input type='text' name='test' value='<?php echo $form["test"]; ?>'/>
<input type='submit'>
</form>
Then in form.process.php
<?php
if (isset($_POST['test')) {
$test = $form['test'] = $_POST['test'];
if (!trim($test)) // empty string? {
$errors[] = "Please fill in test field";
}
}
if (!count($errors)) {
header("Location: formsubmitted.php");
exit;
}