0

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.

Edited by JayGeePee: bold doesn't work in code

3
Contributors
4
Replies
22
Views
3 Years
Discussion Span
Last Post by JayGeePee
1

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.

0

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.

0

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.

0

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.

Edited by JayGeePee

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.