[英]PDO Query - Is this safe from SQL Injection?
I've been reading and asked a question about SQL Injection safe queries and everyone is saying that I should use PDO, so I just enabled my MYSQL PDO extension and made a simple query. 我一直在阅读并询问有关SQL注入安全查询的问题,每个人都说我应该使用PDO,所以我只启用了我的MYSQL PDO扩展并进行了简单的查询。
So this is my code: 所以这是我的代码:
public static function Add($catName, $catDescr = "", $catImgURL = "", $catSubLevel = 0, $catSubID = 0)
{
try
{
include_once "db_config.php";
$DBH = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$STH = $DBH->prepare("INSERT INTO cat (catName, catDescr, catImg, catSubLevel, catSubID)
VALUES ('$catName', '$catDescr', '$catImgURL', $catSubLevel, $catSubID)");
$STH->execute();
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
So everything works and seems safe, but when I do something like this: 所以一切正常并且看似安全,但当我做这样的事情:
Cat::Add("Test Cat", "' OR 1==1 --");
It gives me 它给了我
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
警告:PDOStatement :: execute()[pdostatement.execute]:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near '==1 --', '', 0, 0)' at line 2 in www\\mCat.php on line 25
检查与MySQL服务器版本对应的手册,以便在第25行的www \\ mCat.php第2行'== 1 - ','',0,0)附近使用正确的语法
I suppose it is because I added $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
我想这是因为我添加了
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
in order to see when I have errors. 为了看我什么时候有错误。
Anyway the main question is - is this method safe from SQL injection? 无论如何,主要的问题是 - 这种方法是否可以安全地从SQL注入?
No, it is not - otherwise your experiment wouldn't have come out with an error message. 不,它不是 - 否则你的实验不会出现错误信息。 PDO does not magically know which characters come from variables and which form the query.
PDO并不神奇地知道哪些字符来自变量,哪些字符来自查询。 Instead, you should do something like this:
相反,你应该做这样的事情:
$STH = $DBH->prepare('INSERT INTO cat ' .
'(catName, catDescr, catImg, catSubLevel, catSubID) ' .
'VALUES (?, ?, ?, ?, ?)');
$values = array($catName, $catDescr, $catImgURL, $catSubLevel, $catSubID);
$STH->execute($values);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.