-1
布爾致命錯誤消息我正在學習PHP面向對象,所以我做了一個簡單的登錄頁面與一些類。這裏是我的的login.php文件,其中包含HTML登錄表單,並添加此PHP腳本來測試我怎樣才能查詢從DB:調用成員函數count()在php
require_once 'db.php';
$user = DB::getInstance()->get('admins',array('username', '=', 'alex'));
if(!$user->count()){
echo 'No user';
}else{
echo 'Ok';
}
這是我的db.php中:
<?php
class DB{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct(){
try {
$this->_pdo = new PDO('mysql:host' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
}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->_pdo->prepare($sql)){
$x = 1;
if (count($params)){
foreach($params as $param){
$this->_query->bindValue($x,$param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array()){
if (count($where) === 3){
$operators = array('=','>','>=','<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if (in_array($operator, $operators)){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if (!$this->query($sql, array($value))->error()){
return $this;
}
}
}
return false;
}
public function get($table,$where){
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where){
return $this->action('DELETE ',$table ,$where);
}
public function error(){
return $this->_error;
}
public function count(){
return $this->_count;
}
}
?>
這是我收到的錯誤消息,每當我刷新登錄頁面:
調用一個成員函數count()布爾在login.php中1號線
所以這是login.php中的第1行:
if(!$user->count()){
基本上它返回到我的DB類的最後一個函數是這樣的:
public function count(){
return $this->_count;
}
但我真的不知道爲什麼會發生!請如果你知道如何解決這個問題,請讓我知道......謝謝。
請注意,我沒有添加任何類型的操作文件到登錄頁面,因爲我陷入了這個錯誤! –
我會認爲這是因爲你的「動作」方法返回false,而不是$ this。 –
您的查詢可能有一些錯誤,它似乎不會根據您的錯誤返回'$ this'。它總是返回假。 – Dharam