Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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 www\mCat.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?

like image 825
Stan Avatar asked Feb 05 '11 18:02

Stan


1 Answers

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);
like image 56
phihag Avatar answered Oct 10 '22 15:10

phihag