HellaMad
HellaMad

Reputation: 5374

Are PDO statements automatically escaped?

Are PHP PDO statements automatically escaped, or only prepared statements?

For example, assume that $username and $password are user inputs. Is the following code secure, or is it vulnerable to injection?

$dbh = new PDO("mysql:host=localhost;dbname=mydb", $my_mysql_username, $my_mysql_password);
$sth = $dbh->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$result = $sth->fetch();
if(!$result){
    $dbh->exec("INSERT INTO users (username, password) VALUES ('$username', '$password')");
}

(The above code is purely hypothetical, for example purposes only.)

If they are not automatically escaped, does PDO provide any extra protection over the mysql_ functions in this situation?

Upvotes: 2

Views: 1287

Answers (2)

cHao
cHao

Reputation: 86506

Only prepared statements provide automagic escaping, assuming you don't have some ugliness like magic quotes enabled. And only the data in the params is escaped, not anything that's already in the SQL string when you prepare the statement.

If you want the benefits of auto escaping, you'll have to prepare a statement and feed it the data separately.

$sth = $dbh->prepare("SELECT * FROM users WHERE username=? AND password=?");
$sth->execute(array($username, $password));

Otherwise, you get little to no protection over mysqli_query and friends. (I refuse to even mention mysql_query, because no self-respecting PHP programmer uses it anymore. Oh, wait..damn. Well, that's the only mention it gets here.)

Upvotes: 4

ChocoDeveloper
ChocoDeveloper

Reputation: 14578

They are not escaped. You can see examples here:

http://www.phptherightway.com/#pdo

Upvotes: 2

Related Questions