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?


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.)


They are not escaped. You can see examples here:

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

链接地址: http://www.djcxy.com/p/93758.html

上一篇: PHP PDO:如何防止javascript和html标签注入

下一篇: PDO语句是否自动转义?