I can't seem to figure out why when I submit the form, and it returns with the error message, that it doesn't retain what I've entered into the fields. Here's an example of my input field:
<input type="text" value="<?php if (isset($_POST['the_field'])) echo $_POST['the_field'];?>" name="the_field" id="the_field"/>
I'm using sessions for my error message handling. But I don't think that would make a difference, right? Any ideas?
part of my FORM:
<form action="process.php" method="post" name="edit" id="edit">
<input type="text" value="<?php if (isset($_POST['name'])) echo htmlentities($_POST['name']); ?>" name="name" id="name" class="text" tabindex="1"/>
<input type="text" value="<?php if (isset($_POST['the_field'])) echo $_POST['the_field'];?>" name="the_field" id="the_field"/>
<input type="hidden" value="Create" name="action"/>
<input type="submit" class="btn" value="Create New Project" />
</form>
part of my PROCESS.PHP:
if(isset($_POST)){
switch($_POST['action']){
case 'Create':
$client = $_POST['client'];
if(empty($_POST['name'])){
$_SESSION['error'] = 'You need to enter a project name!';
header('location: add.php');
exit;
}
}
break;
}
Do you think that it's because the NAME field is processed before THE_FIELD and when the NAME errors, it doesn't pass anything back?
It does not matter if isset
, to show what was sent by post
you must to write $_POST['the_field']
like this:
<input type="text" value="<?php echo htmlspecialchars($_POST['the_field']);?>" name="the_field" id="the_field"/>
UPDATE
Don't use sessions
for these kind of things.
if (isset(whatever))
// this
else
// other
In any case you re-populate input with post
values:
<input type="text" value="<?php echo htmlspecialchars($_POST['the_field']);?>"
I mean that you must process all post
stuff BEFORE output html. For example:
if (isset(whatever))
// echo "you posted whatever, great!"
else
// post "value missing, please try again"
<input type="text" value="<?php echo htmlspecialchars($_POST['the_field']);?>"
sessions
are suitable to store permanent data (permanent in a session, of course) To warn users
about invalid input you must to inform them right after post
actions. There is no need to save info in sessions
data.
In conclusion, the normal way to do this is:
<?php
if (input data is valid)
echo 'valid'
else
echo 'invalid'
?>
<input value="<?php echo htmlspecialchars($_POST['the_field']); ?>">
I ended up having to use sessions since I was posting to a process page, which seemed to be the reason, and not SELF. Takes a bit more time but does what I need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.