views:

695

answers:

4

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 with in clause
Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?

+14  A: 

Parameterized Queries

Chad Birch
+1 that's the way to go. Not just because it avoids SQL injection but it also allows RDBMS to do better query execution plan caching.
ssg
+1: always works -- makes injection actually impossible. String manipulation only makes it unlikely for all the cases we tested.
S.Lott
+1: Mush better than trusting your own implementation to not have any edge cases or special syntax vulnerabilities.This also prevents the need to use HTML entities in the database. (I'm looking at you phpBB!)
John Gietzen
+1  A: 

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.

lc
A: 

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.

Alnitak
A: 

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.

K. Brian Kelley