[英]PHP Form Processor Error Passback
我有一个基本的PHP表单页面,其中包含大量数据,一旦完成,这些数据将保存到MySql的约4-5个不同的表中。 由于构造此保存例程将需要一些PHP,因此我希望POST操作不要指向PHP_SELF,而是指向一个单独的PHP文件进行处理。
如果处理器返回错误,则在提交之前将所有常规数据(例如电话号码,电子邮件,邮政编码等)进行验证,然后再将其传递给处理器脚本...
在保持数据输入的同时,指向原始表单页面(HTTP_REFERER)的最佳实践是什么?
表单页面:
<form action="processor.php" action="post">
<!-- lots of fields -->
<input type="submit" id="submitButton" name="Save" value="Save" />
</form>
处理器页面:
<?php
if ( isset($_POST['date']) && ($_SERVER['HTTP_REFERER'] == "form.php") )
{
$errors = false;
//attempt to put data in database
if ( $errors )
{
//Pass back to the form.php page with error message and all data intact
}
}
?>
我之前遇到过此问题,我们如何解决此问题的方法是将所有字段放入会话中,然后使用header(“ Location:form.php”)重定向回form.php。
当数据发布到表单时,我们将$ _REQUEST存储到$ _SESSION ['post'];中。 如果验证失败,我们将其发送回表单,填充字段并取消会话设置。
所以举个例子
$_SESSION['post']['field_a'] = $_REQUEST['field_a'];
$_SESSION['post']['field_b'] = $_REQUEST['field_b'];
有了一些精美的命名约定,您就可以循环执行此操作以使其变得容易。
然后在“表单”页面上,我们只是检查是否有一些数据,或者只是回显数据。
$str_field_a = @$_SESSION['post']['field_a'];
...
<input name="field_a" value="<?php echo $str_field_a; ?>" />
...
unset($_SESSION['post']);
这可能是一种麻烦的方式,但已证明对我们的目的有效。 只是以为我会分享。
我认为您可以使用一系列错误来做到这一点。
将错误标志设置为false(如果发生错误,则将其设置为true,因此不存储在数据库中)。
检查元素1,如果有错误,则将其存储在数组$error['name'] = 'value'
同样,检查所有元素,并使用相同的过程进行存储。
最后,如果将错误标志设置为false,则不要将其存储在数据库中(如果在同一页面上,则可以在要显示错误消息的窗体上访问该数组。)
if(isset($error['elementname'])) echo $error['elementname'];
页面下方。
但是,最好的方法是使用面向对象的方法。
[更新]
我也猜,将整个对象存储在SESSION中并不是一个坏方法
我会发回包含错误和值的form.php帖子。 我在个人项目中使用相同的方法。
if ( $errors ) {
?><form action="form.php" method="post" name="error">
<input type="hidden" name="errcode" value="<?php echo $errorcodes; /*or whatever message*/ ?>" />
<input type="hidden" name="anotherdata" value="anothervalue" />
<?php /*you can add all post datas here as hidden field*/ ?>
</form>
<script type="text/javascript">document.error.submit();</script><?php
}
这类似于我的form.php
//first I set default blank variables for form
$formvalue="";
$formnumericvalue="";
//i set them, yay!
//if I get values from post.php, I update the values
if (isset($_POST['iserror'])) { //you can either echo a error message or update current data here, I'm showing this for both
$formvalue=$_POST['formvalue'];//don't forget to validate these!
$formnumericvalue=$_POST['formnumericvalue']; //don't forget to validate these!
}
//I also do this method for edit forms
//and finally I show the form
?>
<form name="form" method="post" action="post.php">
<input type="text" name="formvalue" value="<?php echo $formvalue; ?>" />
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.