2011-03-25 113 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週期以顯示新創建的記錄