What is the best function to run my strings through to ensure that MySQL injection is impossible?
Also, will it require running it through another function on the way out to make it display correctly?
See also
Are Parameters really enough to prevent Sql injections?
C# Parameterized Query MySQL withinclause
Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?
- 
 What ORM or access layer are you using? What language are you using? For most ORM's, this is trivially handled for you. If you use the JDBC driver properly, this is trivially handled for you. Please provide the language and components you're using.S.Lott– S.Lott2009年04月03日 16:33:52 +00:00Commented Apr 3, 2009 at 16:33
- 
 Duplicate: stackoverflow.com/questions/306668/…, stackoverflow.com/questions/650455/…S.Lott– S.Lott2009年04月03日 16:36:34 +00:00Commented Apr 3, 2009 at 16:36
- 
 @S.Lott: I don't think those count as dupes, since they assume the answer to this one.user27414– user274142009年04月03日 16:38:01 +00:00Commented Apr 3, 2009 at 16:38
- 
 Near duplicate: stackoverflow.com/questions/139199/…S.Lott– S.Lott2009年04月03日 16:38:26 +00:00Commented Apr 3, 2009 at 16:38
- 
 @Jon B: My point is that the question is unsound. SQL Injection is impossible with parameterized queries -- no trust involved. Any string manipulation will work for all the tested cases; you have to trust that they tested all the cases. Consider taking out the element of trust.S.Lott– S.Lott2009年04月03日 16:42:32 +00:00Commented Apr 3, 2009 at 16:42
5 Answers 5
3 Comments
A parameter function.
Humor aside, I mean don't dynamically execute user-entered content as SQL if you can at all avoid it. Pass everything as parameters, and reference them from your query instead. See Chad Birch's answer for a good link explaining this.
Comments
As Chad says, always use parameterized queries to avoid SQL injection.
To answer the second half of your question, if your output is to a web page then always escape any special HTML characters (&, <, >) to protect against script injection.
Comments
Add to parameterized queries the use of input validation within the application. Never trust that the input is clean. Check it. For instance, if it's supposed to be an integer, check to make sure it converts to a numeric value without issue.
Comments
In PHP the best way is to use HTML escaping on strings.
It turns special characters into HTML compliant characters. 
Example: " " (space) transforms into "%20".