I am making a pretty standard PHP sign up form that will validate the data the user entered and then redirect to a page with a success message. I would like to store this data in a database. Should I insert this information into the database before I redirect the page or after it is redirected?
|
|
The pattern for the success case:
And in the failure case:
In your code, this structure looks somewhat like so (pseudocode, obviously):
The reason you're redirecting is that you want to avoid a second database update when the user reloads. Because of this, you need to first store and then redirect. In fact, I recommend you make a habit of calling The reason you don't redirect in the error case is because nothing has been stored yet - if the user reloads, they'll just run into the same error again. If you were to redirect in the error case, you'd have to carry the error messages over the redirect, which is possible but not really pretty, and you'd have an unnecessary round trip. |
|||
|
|
|
The short answer: Make the database update before the redirect. You should always use the get-post-redirect pattern when the user submits a form that alters application data. (Props to @WyattBarnett and @PieterB for answering in comments.) In order to work well with browsers, only GET requests should display a page to the user, and GET requests should never have side-effects like database changes, email messages, etc. So you POST** the form to a processing script, which handles validation, writes to the database, sends emails, whatever... and redirects to another page, which will be requested with GET and will not do any of those things. It just displays stuff. ** Read about REST for an approach to http methods that goes beyond GET and POST. It's most likely not necessary for this application, though. |
|||||||
|
|
You could avoid redirecting, You could have the form Action field submit to the current page and have a snippet of PHP higher up on the page to watch out for the form submission, save the data and show a Thank you message then. For example:
|
|||||||||||||
|
|
Insert the data into database after an individual signs up using a post method and then redirect using header('location:whateverpage.php?message=success') and on the other page use
|
|||
|
|