0

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 form itself to insert into the database, or should the data be posted to another page which inserts data into the database?

oshirowanen
  • 15,297
  • 82
  • 198
  • 350

2 Answers2

4

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

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

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
deceze
  • 510,633
  • 85
  • 743
  • 889