Page 1 of 1
Best way to insert into SQL from form
Posted: Tue May 05, 2009 4:03 pm
by floyd8
Hi Everybody!
I have made a PHP script which generates an HTML form, but I dont know what to do next to get the info from the form into a SQL database. My first instinct is to have the submit action of the form call another PHP script, and pass all the form information via parameters.
Is there a better way to do this? I've noticed that a lot of websites dont have long URL's full of parameters when they submit from forms.
Thanks,
danny
Re: Best way to insert into SQL from form
Posted: Wed May 06, 2009 10:57 am
by allspiritseve
Have your form method set to "post" and you won't have any extra data in the url. Use the variable $_POST to get your data.
I would also suggest having the script that calls the form also be the one that receives the post request. It makes things really simple and you can group shared code if need be. Another best practice is to redirect after you've handled the post, so you're back to a get request. This is called Post-Redirect-Get, and will save you from that annoying message that asks if you want to redirect the form when you press the back button.
Re: Best way to insert into SQL from form
Posted: Thu May 07, 2009 1:57 pm
by floyd8
Thanks!
Re: Best way to insert into SQL from form
Posted: Thu May 07, 2009 2:18 pm
by Christopher
I think it works best if form scripts post to themselves. The basic logic is this:
Code: Select all
// initialize form
if ($form->isValid()) {
// save data (escape values and loop to build UPDATE/INSERT statement)
// redirect to "done" page to fix refresh/resubmit problem
} elseif ($form->isSubmitted()) {
// get errors because form was not valid
} else {
// initialize values because it is 1st time in
}
// show form
Re: Best way to insert into SQL from form
Posted: Thu May 07, 2009 2:56 pm
by allspiritseve
arborint wrote:I think it works best if form scripts post to themselves.
Way to restate what I just said!

Re: Best way to insert into SQL from form
Posted: Thu May 07, 2009 3:53 pm
by Christopher
And we work so well together because I am reading impaired!
