PDO类不返回Count

时间:2016-10-27 23:43:39

标签: php mysql pdo

我编写了一个PDO抽象类,其中包含一些来自StackOverflow的教程和代码,以使我的生活变得更轻松,但PDO仍然是一个痛苦的屁股,让我想知道我是愚蠢还是PDO与良好的旧MySQL相比,学习曲线更大。

无论如何,我要做的是创建一个Statistics类来计算几行而不用左右写主要查询。我正试图计算下面的表格。 联系人+公司+用户

但由于某种原因它不起作用。大多数时候我遇到500错误。看看代码在大多数情况下似乎是正确的,除非我遗漏了一些东西。

所以这里是数据库抽象类 lib / Database.php

class Database{
    private $host      = DB_HOST;
    private $user      = DB_USER;
    private $pass      = DB_PASS;
    private $dbname    = DB_NAME;

    private $dbh;
    private $error;
    private $stmt;

    public function __construct(){
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );
        // Create a new PDO instanace
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }

    # PDO Prepare
    public function query($query){
    $this->stmt = $this->dbh->prepare($query);
    }

    # PDO Count All
    public function countAll($value){
    $sql = "SELECT * FROM `$value`";

    $this->stmt = $this->dbh->prepare($sql);
    try { $this->stmt = $this->execute(); } catch(PDOException $e) { $this->error = $e->getMessage(); }
    return $this->stmt->rowCount();
    }

    # PDO Bind
    public function bind($param, $value, $type = null){
    if (is_null($type)) {
        switch (true) {
            case is_int($value):
                $type = PDO::PARAM_INT;
                break;
            case is_bool($value):
                $type = PDO::PARAM_BOOL;
                break;
            case is_null($value):
                $type = PDO::PARAM_NULL;
                break;
            default:
                $type = PDO::PARAM_STR;
        }
    }
    $this->stmt->bindValue($param, $value, $type);
    }

    # PDO Execute
    public function execute(){
    return $this->stmt->execute();
    }

    # PDO Multiple Records
    public function resultset(){
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    # PDO Single Record
    public function single(){
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
    }

    # PDO Count
    public function rowCount(){
    return $this->stmt->rowCount();
    }

    # PDO Last Insert ID
    public function lastInsertId(){
    return $this->dbh->lastInsertId();
    }

    # PDO Transactions begin / end / cancel
    public function beginTransaction(){
    return $this->dbh->beginTransaction();
    }

    public function endTransaction(){
    return $this->dbh->commit();
    }

    public function cancelTransaction(){
    return $this->dbh->rollBack();
    }

    # PDO Debug Dump
    public function debugDumpParams(){
    return $this->stmt->debugDumpParams();
    }

}

这是统计类 lib / Stats.class.php

class Stats{
      private $_db;

      public function __construct(Database $db){
         $this->_db = $db;
      }

      public function countContacts() {
          $this->_db->query('select count(*) from contacts');
          $this->_db->fetchColumn();
      }

      public function countCompanies() {
          $this->_db->query('select count(*) from companies');
          $this->_db->fetchColumn();
      }

      public function countUsers() {
          $this->_db->query('select count(*) from users');
          $this->_db->fetchColumn();
      }

      public function countInvoices() {
          $this->_db->query('select count(*) from invoices');
          $this->_db->fetchColumn();
      }
}

以下是我如何拨打 index.php

的电话
$database = new Database();
$stats = new Stats($database); 
echo $stats->countContacts();

连接值在后台传递,因为它们包含在模板文件的标题中。

关于我做错什么的任何建议?

1 个答案:

答案 0 :(得分:3)

出于某种原因,您忘记了query()函数实现,它只不过是PDO::prepare()的包装器。因此,按照您的方式调用它是没有意义的。

将以下方法添加到您的班级

public function run($query, $params = NULL){
    $stmt = $this->dbh->prepare($query);
    $stmt->execute($params);
    return $stmt;
}

然后重写您的统计数据收集器:

  public function countUsers() {
      return $this->_db->run('select count(*) from users')->fetchColumn();
  }

请注意,包装器中的所有其他功能都是有害的或无用的。请阅读我的文章Your first database wrapper's childhood diseases以找出原因