Home » Php » php – PDO Query – Is this safe from SQL Injection?

php – PDO Query – Is this safe from SQL Injection?

Posted by: admin July 12, 2020 Leave a comment


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)

        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)");

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

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?

How to&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);