1

I'm wondering if PDO prepared statements can save me from SQL Injection ?

Example: $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

The data I want to insert

$data = array( 'name' => $userInput_1, 'addr' => $userInput_2, 'city' => $userinput_3 );

For instance $userInput_2 is SLQ INJECTION.

$STH = $DBH->("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)");

What will happen after execute in this case ?

$STH->execute($data);

Thank You!

1 Answer 1

0

All input will be properly escaped & quoted. So using PDO prepare / execute should prevent SQL Injection.

From the php manual:

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

2
  • thanks. But will I get exception or the value will be populated into DB ? Aug 16, 2012 at 12:49
  • It depends, strings will be escaped, but a null value will prevent the query from being executed. The result of $STH -> execute($data) will be FALSE $data = array( 'name' => null, 'addr' => "1' AND 1=1", 'city' => false ); $data = array( 'name' => 'null', 'addr' => "1' AND 1=1", 'city' => 'false' ); First one will fail, second one will succeed
    – rsids
    Aug 17, 2012 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.