正确的PDO查询方式

时间:2013-08-13 17:20:59

标签: php sql database postgresql pdo

这是我的连接类。

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注射吗?

谢谢!

2 个答案:

答案 0 :(得分: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'];
}

答案 1 :(得分:-1)

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