SQL Injections - Quick and Easy ways to protect yourself with PHP
MySQL is a lovely way to store data, however as soon as we let users adjust the queries we use it can go pear shaped. Here are some really easy ways to protect yourself from those evil users.
Check Everything!
Seriously, never trust user input. They may not intend to do a SQL inject, but they could still end up doing it anyway. Any data coming from an uncontrolled source should be checked. In the below example I am going to use the if() function:
<?php
if(!is_numeric($_GET['ID'])){ // If it’s not a number
echo ‘Sorry you ID is not a number.’; die();
}
// Do the SQL here.
?>
Hash/Encrypt It
Hashing or encrypting something is essentially changing a string of data into something more manageable. In the below example, I’ll use MD5 as my hashing method. This should remove any dangerous characters which could lead to a SQL error.
<?php
$password = md5($_POST['password']); // run a MD5 on the password
// If the password was 1234, it will now be 81dc9bdb52d04dc20036dbd8313ed055
// do the SQL Query
?>
Of course there are other functions to hash or encrypt something. Take a look at the PHP manual for more of them.
Serialize
Serializing a string creates a storable representation of a value, personally this is my favorite way of putting some data into SQL because it can store arrays (So when I select the field, I get a big array of data). Here is a very quick example on how to do it.
<?php
$data = serialize($_POST['data']);
// do the SQL Query
?>

Client Login