Reputation: 35
I have code in html for a form which needs to be filled. When the button 'OK' is clicked, values are sent to a php script. I use $_POST. Can I display the same form when input is not of the right format but do this only inside my php script?
This is where I check some of my fields but I don't know how to re-display the form.
if (isset($_POST["name"])) {
$name = $_POST["name"];
}
if (isset($_POST["date"])) {
$date = $_POST["date"];
}
Thanks a lot.
Upvotes: 2
Views: 98
Reputation: 15070
You could try something like this:
<?php
foreach($_POST as $key => $value) {
$$key = $value;
}
?>
<form method="post" action="">
<input type="text" name="name" value="<?php echo !empty($name) ? $name : 'Fill in your name'; ?>" />
<input type="text" name="age" value="<?php echo !empty($age) ? $age : 'Fill in your age'; ?>" />
<input type="text" name="what" value="<?php echo !empty($what) ? $what : 'what'; ?>" />
<input type="text" name="ever" value="<?php echo !empty($ever) ? $ever : 'ever'; ?>" />
<input type="submit" value="Go" />
</form>
If you are looking for a php template engine to split the PHP and HTML, I recommand Smarty
To split the HTML and PHP without an engine, you could do something like combine the functions file_get_contents()
and str_replace
like here:
<form method="post" action="">
<input type="text" name="name" value="#_name_#" />
<input type="submit" value="Go" />
</form>
<?php
$template = file_get_contents('template.html');
foreach($_POST as $key => $value) {
$template = str_replace('#_'.$key.'_#', !empty($value) ? $value : '');
}
echo $template;
?>
That way you get the .html file, and replace #_name_#
with the post or a default value.
Still I recommand you to use Smarty
Upvotes: 2