开发者

How to mantain values if submit fails PHP

I have a form that is being validated using PHP server side scripting. The form's action is also to itself. To show multiple erro开发者_Go百科rs, I store it in an array and used foreach to loop through the values and echo it for dislay. I thought i'm finished using PHP validation but I noticed that everytime I submit the form, even though it still contains some errors, all of the values that were inputted resets. Why? When I used javascript, the values remains so whats with PHP?

This is how I set my errors and insert data to db.

if(isset($_POST["submit"]))
{
$lname = $_POST["lname"];

$errors = array();

if(strlen($lname) == 0)
{
$errors[] = "Last name is required";
}

if (!empty(errors))
{
//display errors using foreach loop
}
else
{
//connect and insert data to mysql db
}

}
?>


You perhaps write your HTML form without setting up default values.

<input type="text" name="firstname" />

In the case of an error you should set up a default value. Here an example. Do not forget to sanitize your POST vars before outputting.

<input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" />


in your form's input element code use it like this

<input type="text" name="username" value="<?php if(isset($_POST['username']) echo $_POST['username'];?>">

using isset to check if value exist or not and than echoing it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜