Mevia
Mevia

Reputation: 1564

PDO last insert id returns null or no method found

Ive been searching for long time some solution but none of them are working, tried all the topics from stackoverflow and nothing.

This is my connection script:

private function __construct() {
    try {
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
        $this->_pdo->exec("SET NAMES utf8");
    } catch(PDOException $e) {
        die($e->getMessage());
    }
}

This is my method to query:

public function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }

        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }

    return $this;
}

I had to redone my account activation system and put activation codes to separate table, so when new user come and register i need to grab insert id to place in activation codes table under user_id. The problem is i dont know how to alter script i provided to be able to grab that id.

I tried $this->_pdo->lastInsertId();

and $this->_db->lastInsertId();

in first case i get null all the time in second case i get no method lastInsertId() been found in class

maybe i place it in wrong place or do it wrong, help would be nice, thank you in advance;)

btw im using pdo under mysql server

Upvotes: 0

Views: 116

Answers (1)

Alex
Alex

Reputation: 1573

if($this->_query->execute()) {
    $id = $this->_pdo->lastInsertId();
    $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
    $this->_count = $this->_query->rowCount();
}

Upvotes: 2

Related Questions