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.

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; check the manual that corresponds to your MySQL server version for the right syntax to use near '==1 --', '', 0, 0)' at line 2 in wwwmCat.php on line 25

I suppose it is because I added $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?


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. 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);
链接地址: http://www.djcxy.com/p/93698.html

上一篇: 参考:什么是使用MySQL扩展的完美代码示例?

下一篇: 这是从SQL注入安全吗?