2013-11-14 138 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(); _ –