Home > DeveloperSection > Forums > How to prevent SQL injection in PHP?
jayprakash sharma
jayprakash sharma

Total Post:117

Posted on    April-17-2013 1:26 AM


 1 Reply(s)
 1239  View(s)
Rate this:
Hi Everyone!

If user input is inserted into an SQL query directly, the application becomes vulnerable to SQL injection, like in the following example:

$unsafe_variable = $_POST['user_input'];

mysql_query("INSERT INTO table (column) VALUES ('" . $unsafe_variable . "')");
That's because the user can input something like value'); DROP TABLE table;--, making the query:

INSERT INTO table (column) VALUES('value'); DROP TABLE table;--')

What should one do to prevent this?

Thanks in advance!


Total Post:604

Posted on    April-17-2013 8:55 AM

Hi Jayprakash!

Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This 

way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

    Using PDO:

    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

    $stmt->execute(array(':name' => $name));

    foreach ($stmt as $row) {
        // do something with $row

    Using mysqli:

    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
    $stmt->bind_param('s', $name);


    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        // do something with $row


Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared 

statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=;charset=utf8', 'user', 'pass');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

I hope it resolve your problem!

Don't want to miss updates? Please click the below button!

Follow MindStick