致命错误:在布尔值上调用成员函数count()

时间:2015-10-27 07:43:07

标签: php

class db {

private $_pdo ,
        $_query,
        $_error = false,
        $_results ,
        $_count = 0 ; 

private  function __construct () {
    try {

        $host = config::get('mysql/host');
        $database = config::get('mysql/db');
        $username = config::get('mysql/user');
        $pasword = config::get('mysql/password');

        $this->_pdo = new PDO("mysql:host=$host;dbname=$database", $username, $pasword);

        }  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($tabale , $where) {

    return $this->action('DELETE' ,$table , $where) ;
        }  

public function count() {

    return $this->_count ;
}

 public function error() {

    return $this->_error ;
 }
  } 

index.php

$a = db::getInstance()->get('users',array('username','=','ram')) ;
if(!$a->count()) {

echo "No User" ;
 } else {

echo "OK " ;
  }   

索引文件出错:

  

致命错误:在第4行的布尔值上调用成员函数count()。

2 个答案:

答案 0 :(得分:1)

您的->get(..)方法会返回->action的值boolean 所以这样做:

$a = db::getInstance(); // returns the instance
$a->get('users',array('username','=','ram')); // this return true or false
if(!$a->count()) {
    echo "No User" ;
} else {
    echo "OK " ;
}   

你也错过了->action()的一些$,它需要是:

$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?" ;

答案 1 :(得分:0)

删除 功能中的$table参数的拼写错误。而且下一行的删除查询中也缺少所有符号*