我正在尝试这个 Wrapper,无论如何,当我在 index.php 文件中使用 var_dump($row) 时,我总是会得到“布尔错误”。
这是我的数据库类:
<?php
// database.php
class DB {
protected $_connection = array(); // to map the connection
protected $_dbh; // property which keeps the database handler
protected $_database; // property to keep the database name
protected $_table; // property to keep the table name
protected $_query; // property to keep a query statement
public function __construct() {
// require the database configurations as an array from config.php
$this->_connection = require_once 'config.php';
// define which database driver to use (mysql?) and extract the values as
// variables
extract($this->_connection['connection']['mysql']);
// make the database and table name available to the class
$this->_database = $database;
$this->_table = $table_name;
// Check for PDO driver and create the connection to the database.
try {
$this->_dbh = new PDO($driver.":host=".$host, $username, $password);
} catch (PDOException $e) {
die ('Connection failed: ' . $e->getMessage());
}
}
public function input_query($query) {
$this->_query = $this->_dbh->prepare($query);
return $this;
}
public function execute() {
return $this->_query->execute();
}
public function single() {
$this->execute();
return $this->_query->fetch();
}
public function result_set() {
$this->execute();
return $this->fetchAll();
}
}
然后在我的 index.php 文件中:
<?php
// index.php
require_once 'database.php';
$db = new DB();
$db->input_query("SELECT `name` FROM `names` WHERE `id`=1");
$r = $db->single();
var_dump($r);
如果我这样做
<?php
// index.php
require_once 'database.php';
$db = new DB();
var_dump($db);
我得到一个对象:
object(DB)[1]
public '_connection' =>
array (size=1)
'connection' =>
array (size=4)
'sqlite' =>
array (size=3)
...
'mysql' =>
array (size=6)
...
'pgsql' =>
array (size=6)
...
'sqlsrv' =>
array (size=6)
...
protected '_dbh' =>
object(PDO)[2]
protected '_database' => string 'pagination_demo' (length=15)
protected '_table' => string 'names' (length=5)
protected '_query' => null
但是var_dump($r)总是返回 boolean false ,有时当我使用代码尝试不同的事情时,我会得到'Call to an undefined method DB::single()'或'method on a non-object'类型的消息。
谁能帮我解决这个问题?
非常感谢。问候。