Best practice to deal with form processing

2020-06-24 06:51发布

I was wondering what is the best practice to deal with form processing?

In my case I do something like that:

  • if the user hasn't submited the form
    • display the form
  • else
    • if there are form errors
      • display errors
      • display form again
    • else
      • display a success message
      • (and) display the form again

My problem is that I'm repeating the HTML code for the form for 3 times and I don't think this is a good practice (long file, difficult to read).

标签: php html forms
7条回答
Anthone
2楼-- · 2020-06-24 07:30

Look, it's as simple as an egg!
Just put the same actions in the different order:

  • if the user submited the form
    • if there are form errors
      • fill errors array
    • else
      • record data to database
      • 302 regirect, as it required by HTTP standard
      • exit
  • if we have some errors
    • display errors
    • fill form field values
  • display the form

If you can't live without a success message (a quite useless thing in my opinion) you can display it using get parameter (less preferred) or session (optimal)

oops! it was an old one.

查看更多
登录 后发表回答