Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last ID after insert (always return 0)

Tags:

php

I have an Sql class like this:

        class Sql extends PDO {
            private $connection;
            public function __construct() {
                $this->connection = new PDO("mysql:host=localhost;dbname=myDB", "root", "root");
            }

 (...)

Then I'm trying to insert a data in my db using another class "user.php". Using the "getConection" (sql class method). Like this:

class User {
    private $iduser;
    private $deslogin;
    private $despassword;
    private $datecad;

    (getters & setters)

public function insert() { //query & select are a SQL class method
        $sql = new Sql();
        $sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS))", array(
            ':LOGIN'=>$this->getDeslogin(),
            ':PASS'=>$this->getDespassword()
        ));

            echo $sql->getConnection()->lastInsertId(); //getConnection is a Sql Class method that returns the private connection.
    }

Why my echo always returns 0?

like image 238
Russel Riehle Avatar asked Feb 17 '26 21:02

Russel Riehle


1 Answers

Its because you need same connection object regarding insert query to get last inserted ID but you are creating new connection for getting last inserted ID. That's why you are always getting 0 as result.

See the reference :

http://php.net/manual/en/pdo.lastinsertid.php#120618

EDIT

From your code reference its problem in your insert Have you mark there is one extra closing bracket

change your code to:

$sql->query("INSERT INTO tb_users (deslogin, despassword) VALUES (:LOGIN, :PASS)", array(
            ':LOGIN'=>$this->getDeslogin(),
            ':PASS'=>$this->getDespassword()
        )); //<------there must be only one bracket after::LOGIN, :PASS
like image 197
B. Desai Avatar answered Feb 19 '26 10:02

B. Desai