我在这里遇到PDO :: execute()的问题。问题是我有3个数据库,我想构建一个Singleton类和一个通用查询方法。所以我的DB类结构是这样的:
class DB{
private static $_instance = null;
private $_pdo1, $_pdo2, $_pdo3,
$_query,
$_results,
$_error = false,
$_count = 0;
private function __construct(){
try{
$dns1 = 'mysql:host='.Config::get('mysql1/host').';dbname='.Config::get('mysql1/dbname').'';
$dns2 = 'mysql:host='.Config::get('mysql2/host').';dbname='.Config::get('mysql2/dbname').'';
$dns3 = 'mysql:host='.Config::get('mysql3/host').';dbname='.Config::get('mysql3/dbname').'';
$username1 = Config::get('mysql1/username');
$username2 = Config::get('mysql2/username');
$username3 = Config::get('mysql3/username');
$password1 = Config::get('mysql1/password');
$password2 = Config::get('mysql2/password');
$password3 = Config::get('mysql3/password');
$this->_pdo1 = new PDO($dns1, $username1, $password1);
$this->_pdo2 = new PDO($dns2, $username2, $password2);
$this->_pdo3 = new PDO($dns3, $username3, $password3);
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()){
$this->_error = false;
if($this->_query = $this->_pdo1->prepare($sql) || $this->_query = $this->_pdo2->prepare($sql) || $this->_query = $this->_pdo3->prepare($sql)){
if(count($params)){
$x = 1;
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
echo "Success";
}
}
}
}
第49行中的我收到此错误:
Fatal error: Call to a member function execute() on boolean in /htdocs/DatabaseStructure/classes/DB.php on line 49
第49行:if($this->_query->execute())
也试过但没有成功:
if($this->_query->execute() == TRUE)
if(!$this->_query->execute() == FALSE)
为什么这会给我一个错误?
答案 0 :(得分:3)
在query()
方法
if($this->_query = $this->_pdo1->prepare($sql) || $this->_query = $this->_pdo2->prepare($sql) || $this->_query = $this->_pdo3->prepare($sql)){ ...
问题是由于逻辑OR
条件的错误分组。使用此条件语句$this->_query
将始终评估为true
或false
。
以下是两个示例来说明这一点:
要使其正常工作,请更改条件语句,如下所示:
if(($this->_query = $this->_pdo1->prepare($sql)) || ($this->_query = $this->_pdo2->prepare($sql)) || ($this->_query = $this->_pdo3->prepare($sql))){ ...
所以你的query()
方法应该是这样的:
public function query($sql, $params = array()){
$this->_error = false;
if(($this->_query = $this->_pdo1->prepare($sql)) || ($this->_query = $this->_pdo2->prepare($sql)) || ($this->_query = $this->_pdo3->prepare($sql))){
if(count($params)){
$x = 1;
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
echo "Success";
}
}
}
要测试代码,请运行如下的简单查询:
DB::getInstance()->query("SELECT * FROM users");