Author Topic: How to stop SQL Injection  (Read 4977 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
How to stop SQL Injection
« on: August 22, 2009, 04:43:59 PM »
To stop SQL Injection you should use:
For numeric/integer values:


$foo = intval($foo);www.php.net/intval

And for any other data:

$foo = mysql_real_escape_string($foo);www.php.net/mysql_real_escape_string

Do never ever trust the user or think "Nah, they won't do or try this". You can also use preg_* functions to filter the input for what it needs to be.
For example if you only want to allow characters from a-z you can do:


$foo = preg_replace('/[^a-z]/i', null, $foo);www.php.net/preg_replace

Or if you have a select for example, and you want to make sure the submitted value exists in the select, do something like:

$allowed_values = array('foo', 'bar', 'etc');if (!in_array($_POST['select'], $allowed_values)){    // Handle error}