php - Return Last Insert ID with PDO -
i have class , extend return id of last inserted row keep getting error:
fatal error: call undefined method pdostatement :: lastinsertid () on line 49
my code:
class db { public static $instance = null; private $_pdo = null, $_query = null, $_error = false, $_results = null, $_count = 0, $_lastid = 0; private function __construct() { try { $this->_pdo = new pdo('mysql:host=' . config::get('mysql/host'). '; dbname=' . config::get('mysql/db') . '; charset=utf8', config::get('mysql/username'), config::get('mysql/password') ); } catch(pdoexeption $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; if($this->_query = $this->_pdo->prepare($sql)) { $x = 1; if(count($params)) { foreach($params $param) { $this->_query->bindvalue($x, $param); $x++; } } if($this->_query->execute()) { $this->_results = $this->_query->fetchall(pdo::fetch_obj); $this->_count = $this->_query->rowcount(); $this->_lastid = $this->_query->lastinsertid(); // <- erro } else { $this->_error = true; } } return $this; }
according php docs, lastinsertid method of pdo object, not stmt object (which referencing via $this->_query). try this:
$this->_lastid = $this->_pdo->lastinsertid();
Comments
Post a Comment