2016-10-27 3 views
0

PDO 추상화 클래스를 작성하여 StackOverflow의 일부 자습서와 코드 비트를 사용하여 내 인생을 좀 더 쉽게 만들었지 만 PDO 스틸은 엉덩이에 통증이있는 ​​것 같고 나도 어리석은 경우 또는 PDO가 좋은 오래된 MySQL에 비해 더 큰 학습 곡선을 가지고 있다면.PDO 클래스가 반환되지 않음 Count

어쨌든 내가 뭘 하려는지는 중요한 쿼리를 오른쪽과 왼쪽으로 쓰지 않고 몇 개의 행을 세는 통계 클래스를 만드는 것입니다. 나는 다음 테이블에 대한 카운트를 얻으려고합니다. 연락처 + 회사 + 사용자

하지만 어떤 이유로 작동하지 않습니다. 대부분 나는 500 에러를 쳤다. 그리고 코드를 살펴보면, 뭔가 빠뜨린 것이 아니라면 대부분의 부분에서 정확하다고 보입니다. 그래서 여기

은/

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(); 
    } 

} 

Database.php 데이터베이스 추상화 클래스 lib 디렉토리 그리고 여기/

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(); 
     } 
} 

Stats.class.php 통계 클래스 lib 디렉토리 그리고 여기 내가 전화를하는 방법 index.php

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

연결 값은 템플릿 파일의 헤더에 포함되어 있으므로 백그라운드에서 전달됩니다.

무엇이 잘못 되었습니까?

+1

켜기 ERROR_REPORTING - 무슨 내용입니까? – Dan

+1

500 오류 : 서버 오류; 로그를 확인하십시오. –

+0

@ Fred-ii- 나는 500이 서버 오류라고 알고 있지만, 500 오류와 관련하여 타임 스탬프에 대한 아파치 오류 로그에는 오류 로그가 없습니다. 그러나 나는 이것을 발견 ... PHP 구문 분석 오류 : 구문 오류, 예기치 않은 ',', 변수 (T_VARIABLE) /Applications/MAMP/htdocs/sbs/lib/stats.class.php 15 행에 기대하고있다. – 0111010001110000

답변

4

어떤 이유에서든 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이라는 내 기사를 읽으십시오.

+0

그래서 Database 클래스의 __construct 부분에 무엇을 권하고 싶습니까? – 0111010001110000

관련 문제