问题
i am using PDO package to manage my application database.
i use PDO::prepare , PDOStatement::execute and somtimes PDO::quote , PDO::query / PDO::exec to excute my queries
are PDO::prepare and PDO::quote completely secure? or shoud i make more work to properly validate my inputs.not only for databaase but for php code either
Thank you
回答1:
There's nothing magic about using prepare(). You can interpolate unsafe variables into a string and then prepare that string. Boom—SQL injection. Preparing a statement doesn't make it safe.
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = {$_POST['id']}"); // UNSAFE!
What makes it safe is using parameters.
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = ?");
$stmt->execute([$_POST['id']]); // SAFE!
Naturally, people say "use prepared statements" because you must use prepared statements to use parameters. But just saying "use prepared statements" kind of misses the point, and some developers get the wrong understanding.
The PDO quote() method is also safe, but I find it simpler and easier to use parameters.
$idQuoted = $pdo->quote($_POST['id']);
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = $idQuoted");
来源:https://stackoverflow.com/questions/44446229/are-pdoprepare-and-pdoquote-completely-secure