Securing From SQL Injection With PDO API?

Possible Duplicate:
Are PDO prepared statements sufficient to prevent SQL injection?

my main concern with rolling out a new API Which I have been working on for a few days is the Security.

I'm a beginner to the PDO usage, but know the main structure. but I have no idea on how to protect the query from SQLInjection.

My code is Listed below:

<?php
    $Start = new Db();
    class Db 
    {
        private $dbh = null;

        public function __construct()
        {
            $this->dbh = new PDO('mysql:host=localhost;dbname=pdo', 'root', 'xxxxx');
        }

        public function PDOFetch($Var)
        {
            $sth = $this->dbh->prepare("$Var");
            $sth->execute();
            $result = $sth->fetchAll();
            return $result; 
        }

        public function PDONumb ($Var)
        {
            $sth = $this->dbh->prepare("$Var");
            $sth->execute();
            $count = $sth->rowCount();
            return $count;
        }

        public function PDODel ($Var)
        {
            $Delete = $this->dbh->exec("$Var");
            return $Delete;
        }

        public function PDOQuery ($Var)
        {
            $Query = $this->dbh->query("$Var");
            return $Query;
        }
    }
?>

How would I go About protecting from SQL Injection and other vulnerabilities?

Edit:

Queries Being passed into the API is being done from the "index.php" page for example.

A line would be:

    $Num = $Start->PDONumb("SELECT * FROM news");

But later, when I have covered my tracks with this. I want to go more advanced using this, so it will pass variables which user defines (hence the SQL injection question)

but at the moment, queries being passed through are defined by the administrator.


We can't tell without seeing the SQL that you're passing in. If you're creating insecure SQL statements with untrusted data, then it doesn't matter if they get executed in PDO or not. You'll still be open to SQL injection.

For example, if you get $userid from the web and you build:

$sql = "SELECT * FROM users WHERE userid=$userid";

that SQL statement is open for SQL injection, because if the value of $userid is 0; DROP TABLE users; 0; DROP TABLE users; , then the SQL you will create will be

SELECT * FROM users WHERE userid=0; DROP TABLE users;

and it doesn't matter if you execute that through PDO or not: You're still executing code that a bad guy has sent you.

To use PDO properly, you need to bind your parameters.


Unrelated to your question, but an important point that novices often run into: It's unnecessary to put double quotes around your single variables. Your code

$Delete = $this->dbh->exec("$Var");

would be better written as

$Delete = $this->dbh->exec($Var);
链接地址: http://www.djcxy.com/p/93744.html

上一篇: 此代码是否使用PDO安全?

下一篇: 使用PDO API保护SQL注入?