Member Avatar for JayGeePee

I'm having issues with repopulating my input fields after being submitted if there is an error.

I've tried the simple <?php if(isset($_POST['value'])){echo $_POST['value'];} ?>
That doesn't work. And I'm thinking it's because of how I have my else statements set up. I am currently using get to repopulate my fields, and it's working but I'm not so sure it's the best practice.

Example of original code:

(form-check.php)

<?php
if(isset($_POST['firstname'])) {
$firstname = $_POST['firstname'];
// do something
} else {
    header("Location: index.php?error=This field is required!");
}

?>

(index.php)

<form action="form-check.php" method="POST">
<input type="text" name="firstname" value="<?php if(isset($_POST['firstname'])){echo htmlentities($_POST['firstname']);} ?>" />
<input type="submit" value="Submit" />

<?php if(isset($_GET['error'])){echo $_GET['error'];} ?>

Example of working code:

(form-check.php)

<?php
if(isset($_POST['firstname'])) {
$firstname = $_POST['firstname'];
// do something
} else {
    header("Location: index.php?error=This field is required!&firstname=$firstname");
}

?>

(index.php)

<form action="form-check.php" method="POST">
<input type="text" name="firstname" value="<?php if(isset($_GET['firstname'])){echo htmlentities($_GET['firstname']);} ?>" />
<input type="submit" value="Submit" />

<?php if(isset($_GET['error'])){echo $_GET['error'];} ?>

I'm using my else statement and passing my values and error through the same GET method by using header().
Like I said it's working this way but I wanted to ask some opinions on it.

Member Avatar for diafol

Number of options. You could use Ajax so that values stay in situ. You could use session vars to store form values. You could even use cookies (yuk). You could also use a query string but that's really ugly.

Member Avatar for JayGeePee

So what you're saying is the way I have the code set up now is not good? Lol!
I'm not real good with ajax, sessions or cookies so I may re do my code. I just rescently got serious about learning php, so I'm still new to it. Thanks for the input diafol.

Your $_POST values are lost because the redirect in form-check.php
You can also put the code from form-check.php into the index.php file.
And than have your form action point to index.php.

Member Avatar for JayGeePee

I figured I'd have to do that. I seen someone do it this way and figured I'd give it a try. Now I see why most people don't do it this way. I've already put the php in my index page and echo'd the errors out. Now I can work with everything.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.