How to write php->mysql queries?
Is there any good tutorial that has all the basic rules for writing queries to store $_Post vars from php to mysql? Like when to use backticks and singleqoutes, and how to safely write code with functions like get_magic_quotes_gpc()
?
Another thing is, assuming there is no javascript validation(since the user can easily turn it off), how should I handle empty form fields being sent as empty $_post variables and开发者_开发知识库 throwing errors? Do I have to use isset()
call on all the post variables?
What is the best way to handle users turning off javascript validation on a form?
Escaping and magic quoting will not prevent SQL injection; SQL injection is bad; you should use prepared statements.
An introduction to secure database handling can be found here.
As Tobias suggested, you can use mysql_real_escape_string() to escape each $_POST variable. This does not fully protect against SQL injection, but it's still a necessity. If you want to learn about correct quoting, check this page out.
When I used to write procedural style apps, I would use isset() to check for all required fields, and would also validate them against any other specific rules using if statements that got pretty long. You could initialise an error variable before the validation is done, and if any $_POST variables fail validation, the message relating to that variable is appended to the error variable. You could then redirect back to the form and echo the full error message at the top of the form.
This is pretty messy to code though, and depending on how many forms you have, can get really tedious. Are you using a framework? Because form validation is such an irritating, yet absolutely required task, most frameworks have built in form validators. I personally use Codeigniter, which makes validation trivial. You just set the rules, it'll handle the execution and generation of a user friendly error message. It will also escape the variables, and has optional XSS filtering. You can check out Codeigniters validation at Google (sorry, I can't post 2 links in this post because my rep is under 10)
Use mysql_real_escape_string()
http://php.net/manual/de/function.mysql-real-escape-string.php to sanitize the user´s input.
Validation should be made with PHP, JavaScript could be used for this, but then just for a greater user experience, the safety checks have to be done serverside!
精彩评论