我需要知道我写的PDO扩展是否在语法和语义上都有效。我一直在var_dumping()我的连接变量,当变量被传递给构造函数(具有正确的值)时,我无法从数据库中实际获取任何内容。
我已经在PHP手册上研究过PDO类,从我发现的我正在使用的类几乎与维基页面的示例部分中给出的扩展类相同。
这是我的代码:
class DBConnector extends PDO
{
private $host;
private $username;
private $password;
private $db;
private $dns;
public function __construct($host, $username, $password, $db)
{
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->dns = "mysql:dbname=".$this->db.";host=".$host;
$connection = parent::__construct($this->dns, $this->username, $this->password);
}
}
这是一个测试查询,返回一个数组,其中没有任何内容。数据库中有数据,所以显然有些不正确。
function testQuery()
{
global $connection;
$query = "
SELECT * FROM users
";
$stmt = $connection->prepare($query);
$result = $stmt->fetchAll();
}
我做错了吗?
答案 0 :(得分:11)
试试这个:
class DBConnector extends PDO
{
private $connection;
private $host;
private $username;
private $password;
private $db;
private $dns;
public function __construct($host, $username, $password, $db)
{
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->dns = "mysql:dbname=".$this->db.";host=".$host;
$this->connection = parent::__construct($this->dns, $this->username, $this->password);
$this->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function testQuery()
{
$query = "SELECT * FROM a";
$stmt = $this->prepare($query);
if($stmt->execute()){
return $stmt->fetchAll();
}
return array();
}
}
$tg = new DBConnector('localhost', 'root', '', 'test');
$t = $tg->testQuery();
print_r($t);
$ connection是DBConnector :: __构造的本地,我看不到任何全局。所以它不会存在于你的testQuery函数中。通过将函数移动到类中,并创建连接属性,可以很容易地使用它。
答案 1 :(得分:3)
您需要执行查询。
function testQuery()
{
global $connection;
$query = "
SELECT * FROM users
";
$stmt = $connection->prepare($query);
if($stmt->execute()){
$result = $stmt->fetchAll();
}
}