prevent sql injection

Hi there! Today In this post I will mention few of the methods which is usually used in php application to prevent SQL injections.
It is said, “Never Trust Your User’s Input”. Preventing and cleaning user input in your php code is always a good and recommended practice.

1) Using mysql_real_escape_string() function:

Use if mysql_real_escape_string() is always a good practice into your code, but we can make it even better, consider following Code:

A BAD PRACTICE:
Example:

A GOOD PRACTICE:

Example I:

Example II:

Also, if possible set your default charset to UTF8 using mysql_set_charset() function, it will be an another good approach.

2) PDO Prepared statements:

Following code will be quiet safe for pdo:

3) Using mysqli prepared statement:

References:

http://en.wikipedia.org/wiki/SQL_injection
http://hakipedia.com/index.php/SQL_Injection
http://es1.php.net/mysqli_prepare
http://es1.php.net/manual/en/mysqli-stmt.execute.php
http://php.net/manual/en/pdo.prepared-statements.php