2013-11-14 130 views
1

我正在使用CakePHP 2.4.1,我需要直接訪問PDO,以便從我的MySQL DB中逐行抽取一組記錄。CakePHP PDO準備語句

這是一件我使用代碼和正在產生的問題:然而,一旦

  // Get PDO access 
    $this->_pdo = $this->Event->getDataSource(); 

    try { 

     // Start transaction 
     $this->_pdo->begin(); 

     // All the past events 
     $stm = $this->_pdo->prepare("SELECT `id` FROM `events` WHERE `stop_time` < '" . date('Y-m-d H:i:s') . "'"); 

     // Loop through the events 
     if($stm->execute()) { 
      while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
       // .... 
      } 
     } 

     // Commit transaction 
     $this->_pdo->commit(); 

    } catch (Exception $e) { 

     // Rollback transaction 
     $this->_pdo->rollback(); 

     CakeLog::write('error', $e); 
    } 

我啓動腳本,我回去此錯誤消息

PHP Fatal error: Call to undefined method Mysql::prepare() 

但我已經看到這個框架支持PDO,特別是prepare()函數。 CakePHP PDO Documentation

任何想法?

非常感謝

+0

只是爲了記錄在案,你都出現在這裏可以使用['DboSource' API(http://api.cakephp.org/2.4/class-DboSource.html完成)由'Mysql'數據源實現。 – ndm

回答

4

其實你正在使用的類是http://api.cakephp.org/2.4/class-DataSource.html 沒有prepare()方法那裏。使用此獲得PDO

$myPDO = $this->SomeModel->getDataSource()->getConnection(); 
+0

非常感謝。爲了糾正我的代碼,使用你的解決方案,從而有權訪問PDO,_ $ this - > _ pdo-> begin(); _必須用_ $ this - > _ pdo-> beginTransaction(); _ –