PHP OOP布尔错误

时间:2018-03-15 05:44:00

标签: php

我收到以下错误:

  

致命错误:未捕获错误:在C:\ xampp \ htdocs \ pianocourse101 \ index.php中调用boolean上的成员函数count():5堆栈跟踪:#0 {main}抛出C:\ xampp \ htdocs第5行\ pianocourse101 \ index.php

我一直想知道我的db.php或index.php中我的函数计数的错误部分是否?这是我的代码:

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; 
        // set the error to false so that we are not returning a previous error
       if($this->_query = $this->_pdo->prepare($sql)) {                           
    // check to see if query has been prepared properly
          $x=1;
          if(count($params)) {             // check to see if need to bind 
                                           anything
             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();        // to query a 
            database securely by binding parameters and preventing sql 
              injections
          } else {
               $this->_error = true;
          }
       }

       return $this;      // return the currenct object we are working with
    }

    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;
             }// to check to see if operator is inside the operators .... We do a     ? so that we can bind the value on
          }
       }
       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;
    }
}

的index.php

<?php
require_once 'core/init.php';

$user = DB::getInstance()->get('users', array('username', '=', 'alex'));             

if (!$user->count()) {
    echo 'No user';
} else {
    echo 'OK!';
}

1 个答案:

答案 0 :(得分:0)

您的get()方法将始终失败,因为它会生成无效的SQL查询。

说明

如果我们接受您的请求:

$user = DB::getInstance()->get('users', array('username', '=', 'alex'));

并将其分解以查看会发生什么(这与上述相同):

// This will work and return an instance of DB
$db = DB::getInstance();

// Will always fail and return false, since the get() method fails
$user = $db->get('users', array('username', '=', 'alex'));

// Since user is false (a boolean), it doesn't have any methods
$user->count()

那么,为什么会失败?让我们看看您的数据库课程。

让我们从get()方法开始:

public function get($table, $where){

    // This is calling an internal method called "action()" passing three values

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

以及失败的地方,action()方法:

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)) { 

            // The get() method passed 'SELECT *' to this method, so the below string will be
            // "SELECT * * FROM users WHERE username = ?" 
            // (hint: it's the double * * that's invalid) .

            $sql = "{$action} * FROM {$table} WHERE {$field} {$operator} ?";
            if(!$this->query($sql, array($value))->error()) {

                // Since the query fails, it will never come here

                return $this;
            }
        }
   }

   // Since the query fails (is invalid), this is what it will return

   return false;
}

解决方案

快速解决方法是更改​​action()方法:

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

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

正如我在评论中提到的,您应该研究PDO的正确错误处理。或者更好的是,使用一些久经考验的数据库库。

您提到您是PHP的新手,并且正在阅读一些教程,建议您逐步学习基础知识。