2011-03-25 167 views
0

更新1:插入一条记录

我从来没有碰到过PRG之前,没有任何人有一个链接到PHP一些示例代码显示在行动呢?

原题:

什么是更好的,为什么?

如果我有一个注册表单,我应该发回表单本身插入到数据库中,还是应该将数据发布到另一个将数据插入数据库的页面?

+0

发布自我,验证,插入,重定向。 – 2011-03-25 08:44:55

回答

4

因为应该在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

+0

为该链接+1 ... – 2011-03-25 08:46:32

+0

请参阅原始问题中的**更新1:**。 – oshirowanen 2011-03-25 08:52:06

+0

@oshirowanen在这里你去 – 2011-03-25 08:55:47

0

通常的逻辑是这样的:

<?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> 

此:

  • 坚持形式的数据,直到它是有效的
  • 输出验证消息
  • 调用重定向/ GET周期以显示新创建的记录