Best way to insert into SQL from form

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
floyd8
Forum Newbie
Posts: 2
Joined: Tue May 05, 2009 3:53 pm

Best way to insert into SQL from form

Post 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
User avatar
allspiritseve
DevNet Resident
Posts: 1174
Joined: Thu Mar 06, 2008 8:23 am
Location: Ann Arbor, MI (USA)

Re: Best way to insert into SQL from form

Post 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.
floyd8
Forum Newbie
Posts: 2
Joined: Tue May 05, 2009 3:53 pm

Re: Best way to insert into SQL from form

Post by floyd8 »

Thanks!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Best way to insert into SQL from form

Post 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
(#10850)
User avatar
allspiritseve
DevNet Resident
Posts: 1174
Joined: Thu Mar 06, 2008 8:23 am
Location: Ann Arbor, MI (USA)

Re: Best way to insert into SQL from form

Post by allspiritseve »

arborint wrote:I think it works best if form scripts post to themselves.
Way to restate what I just said! :wink:
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Best way to insert into SQL from form

Post by Christopher »

And we work so well together because I am reading impaired! :drunk:
(#10850)
Post Reply