我无法进行查询。
这是我的代码,我连接到数据库并尝试查询。
编辑:
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');
这是我的代码,我没有任何错误,但仍然无法正常工作.....
答案 0 :(得分: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);