0

这是我的连接类。

class Database {
    private $host;
    private $port;
    private $dbname;
    private $username;
    private $password;

    function __construct($host, $port, $dbname, $username, $password) {
        $this->host = $host;
        $this->port = $port;
        $this->dbname = $dbname;
        $this->username = $username;
        $this->password = $password;

        try {
            $conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
            echo "PDO connection object created";
        }
        catch(PDOException $e) {
            echo $e->getMessage();
        }
    }

}

$db = new Database('host','5432','eu','eu','eu');

你能帮我做正确的 QUERY 类,这样可以避免 sql 注入吗?

谢谢!

4

2 回答 2

1

我从你的课中取出了所有无用的东西并添加了所需的查询。它将提供与 PDO 本身一样多的保护。

class Database
{
    function __construct($host, $port, $dbname, $username, $password) {
        $dsn = "pgsql:host=$host;port=$port;dbname=$dbname";
        $this->conn = new PDO($dsn, $username, $password);
    }
    function query($query, $bind) {
        $stmt = $this->conn->prepare($query);
        $stmt->execute($bind);
        return $stmt;
    }
}
$db   = new Database('host','5432','eu','eu','eu');
$sql  = "SELECT * FROM users WHERE age > ? AND sex = ?";
$stmt = $db->query($sql, array(20,'F'));
$data = $stmt->fetchAll();
foreach ($data as $row) {
    echo $row['name'];
}
于 2013-08-13T19:26:09.670 回答
-1

您可能想查看来自 Tutsplus 的优秀教程。它们涵盖了您需要的内容(准备好的陈述)以及更多内容!我还建议extend使用 PDO 而不是制作包装类 - 它通常更灵活。

于 2013-08-13T17:27:04.113 回答