user22515
user22515

Reputation: 35

Display the input form

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

Answers (1)

Ron van der Heijden
Ron van der Heijden

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

EDIT

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:

Template.html

<form method="post" action="">
    <input type="text" name="name" value="#_name_#" />

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

PHP

<?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

Related Questions