开发者

Inserting a record

UPDATE 1:

I've never come across PRG before, does anyone have a link to some sample code in PHP showing this in action?

ORIGINAL QUESTION:

What is better and why?

If I have a registration form, should I post back to the f开发者_StackOverflow社区orm itself to insert into the database, or should the data be posted to another page which inserts data into the database?


It doesn't really matter as you ought to do HTTP redirect after POST request anyway.

However, most common practice is to send to the same URL, as it's described in /POST/Redirect/GET pattern

a concise example:

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

where form.tpl.php is a template contains HTML form with PHP code to display form values out of the $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>

and main.tpl.php is a main site template as it's described here: Using Template on PHP


The usual logic is this:

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

This:

  • persist the form data until it is valid
  • outputs validation messages
  • invokes a redirect/GET cycle to display the newly created record
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜