更新1:插入一条记录
我从来没有碰到过PRG之前,没有任何人有一个链接到PHP一些示例代码显示在行动呢?
原题:
什么是更好的,为什么?
如果我有一个注册表单,我应该发回表单本身插入到数据库中,还是应该将数据发布到另一个将数据插入数据库的页面?
更新1:插入一条记录
我从来没有碰到过PRG之前,没有任何人有一个链接到PHP一些示例代码显示在行动呢?
原题:
什么是更好的,为什么?
如果我有一个注册表单,我应该发回表单本身插入到数据库中,还是应该将数据发布到另一个将数据插入数据库的页面?
因为应该在POST请求后做HTTP重定向并不重要。
然而,最常见的做法是要发送到相同的URL,因为它在/POST/Redirect/GET模式
一个简洁的例子定律描述:
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
//if no errors - saving data
// ...
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
$tpl = 'form.tpl.php';
include 'main.tpl.php';
?>
其中form.tpl.php
是模板包含HTML表单与PHP显示表格值的代码$form
array
<? foreach ($err as $line): ?>
<div style="error"><?=$line?></div>
<? endforeach ?>
<form method="POST">
<input type="text" name="name" value="<?=$form['name']?>"><br>
<textarea name="comments"><?=$form['comments']?></textarea><br>
<input type="submit"><br>
</form>
和main.tpl.php
是因为它是这里所描述的主要网站模板:Using Template on PHP
为该链接+1 ... – 2011-03-25 08:46:32
请参阅原始问题中的**更新1:**。 – oshirowanen 2011-03-25 08:52:06
@oshirowanen在这里你去 – 2011-03-25 08:55:47
通常的逻辑是这样的:
<?php
if ($_POST) {
... validate the data ...
if ($valid) {
... insert into database ...
$id = mysql_last_insert_id();
header('Location: /view.php?id=' . $id);
exit;
}
}
?>
...
<form action="thispage.php">
<input name="foo" value="<?php echo isset($_POST['foo']) ? htmlentities($_POST['foo']) : null; ?>">
<?php if (... foo failed validation ...) : ?>
<p class="error">Please enter a valid foo!</p>
<?php endif; ?>
<input type="submit">
</form>
此:
发布自我,验证,插入,重定向。 – 2011-03-25 08:44:55