PHP

Preventing MySQL Injection in PHP

Security issues like MySQL injection can only be corrected by using two functions

mysql_real_escape_string (php manual) and

stripslashes (php manual).

 

Example:

$safe_string = mysql_real_escape_string(stripslashes($tainted_string));

 

To make your life a little easier just create a suitable function for this line of code:

function checkString($value) {
 
    return mysql_real_escape_string(stripslashes($value));
 
}

then you have,

$safe_string1 = checkString($tainted_string1);
 
$safe_string2 = checkString($tainted_string2);

 

Don’t forget to validate empty fields before querying a MySQL database.

if ( !isset($value) || trim($value) == "")

or by using the empty() function!