0

我无法查询。

这是我的代码,我连接到数据库并尝试查询。

编辑 :

class DatabaseConnection {
    private $host;
    private $port;
    private $dbname;
    private $username;
    private $password;
    private $query;


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


    function setQuery($query) {
        $this->query = $query;
        $sth = $db->prepare($this->query);
        $sth->execute();
        $result = $sth->fetchAll();
        var_dump($result);
    }

}

$db = new DatabaseConnection('144.76.6.45','5432','eu','eu','eu123');
$db->setQuery('SELECT * FROM user');

这是我的代码,我没有任何错误,但仍然无法正常工作.....

4

1 回答 1

0

根据查询的类型,您将希望在执行后获取数据。看看fetch()fetchAll()方法。

$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);

或使用循环并逐行获取

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    var_dump($row);
}

编辑后

尝试替换:

$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");

$this->db = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");

然后prepare在其上调用方法:$sth = $this->db->prepare($this->query);而不是$sth = $db->prepare($this->query);

于 2013-08-13T18:12:15.207 回答