Best way to deal with SQL injection for PHP?

dave_15_uk

New member
Use strong validation. If the input is a number, use the is_numeric function to make sure no other characters are being inserted. Only allow data that you expect to be inserted
 
mysql_real_escape_string is a hack.
It's a decent hack, but it's a hack. It's a band-aid, not a cure.

The right solution is to use Parameterized Queries, AKA prepared statements. Or even better...use stored procedures. You really shouldn't be writing SQL in PHP. You write SQL in your database. You call it from PHP.

There are a few types of problems that aren't easily solved like this: Where the UI lets the user create some arbitrary combination of query parameters, strung together with AND's, OR's, LIKES' etc. You may still need to use dynamic SQL here. An IN clause is also hard to parameterize.

But that's probably 0 to 1% of your queries. For the rest, just do it right and stop worrying about it.
 
Back
Top