[英]PDO query doesn't work
I can't do a query. 我无法查询。
This is my code, where I connect to database and try to query. 这是我的代码,在这里我连接到数据库并尝试查询。
EDIT : 编辑:
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');
This is my code, I don't have any errors, but still it doesn't work..... 这是我的代码,我没有任何错误,但仍然无法正常工作.....
Depending on the type of query you will want to fetch data after executing it. 根据查询的类型,您将希望在执行数据后获取数据。 Take a look at fetch()
and fetchAll()
methods. 看一下fetch()
和fetchAll()
方法。
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
or use a loop and fetch row by row 或使用循环并逐行获取
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
var_dump($row);
}
after your edit : 编辑后 :
Try to replace: 尝试更换:
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
with 与
$this->db = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
and then call prepare
method on it: $sth = $this->db->prepare($this->query);
然后在其上调用prepare
方法: $sth = $this->db->prepare($this->query);
instead of $sth = $db->prepare($this->query);
而不是$sth = $db->prepare($this->query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.