Return the last ID with PDO in PHP

Asked

Viewed 401 times

0

I need to get the last id inserted, I tried using lasInsertId but I’m not getting it, I don’t know if I ran wrong or so on, but here’s the code of my connection and PDO functions. The error remains in Getultimoid().

//função para fazer conexão com o banco de dados
private function Conectar(){

    $options = array(
        //trasforma o padrao do banco para utf8
        PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8",
        //traz algum alerta de erro
        PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING
    );
    $link = new PDO("mysql:host={$this->host};dbname={$this->banco}", $this->user, $this->senha, $options);

    return $link;
}

//função que executa a query
function ExecuteSQL($query, array $params = NULL){
    $this->obj = $this->Conectar()->prepare($query);

    // verificando a quantidade de parametros passados na url
    if(@count($params) > 0){
        foreach($params as $key => $value){
            $this->obj->bindvalue($key, $value);
        }
    }

    return $this->obj->execute();
}
//função para listar os meus elementos
function ListarDados(){
    return $this->obj->fetch(PDO::FETCH_ASSOC);
}

//função para mostrar um quantidade de dados
function TotalDados(){
   return $this->obj->rowCount(); 
}

//função que armazena os itens dentro de um array
function GetItens(){
    return $this->itens;
}

function GetUltimoID(){
    return $this->obj->lastInsertId();
}
  • Looks like you’re running the method lastInsertId on the return of $this->Conectar()->prepare, which will be an instance of PDOStatement. You must call the method in the instance of your connection or transaction.

  • If I switch to $this->Connect()->lasInsertId(); It returns me id 0

  • Because there you are creating a new connection. Try to analyze the code you are writing and understand, in fact, what has been done.

  • And that’s why I’m asking for help, I don’t know how to structure, because I’m learning and in the videos classes I saw he doesn’t explain right, I don’t know how to call this instance

1 answer

2

The problem is in your call to lastInsertId. Are you calling the method in $this->obj, that defined as the return of prepare:

$this->obj = $this->Conectar()->prepare($query);

The return of prepare is an instance of PDOStatement and this class does not have the method lastInsertId. You should call such a method directly over your connection or transaction.

His method Conectar always returns a new connection with the database at each call. This is quite unusual and probably unnecessary since you can reuse the connection. So, you can store the connection:

private function Conectar(){

    if (!isset($this->link)) {
        $options = array(
            //trasforma o padrao do banco para utf8
            PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8",
            //traz algum alerta de erro
            PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING
        );
        $this->link = new PDO("mysql:host={$this->host};dbname={$this->banco}", $this->user, $this->senha, $options);
    }

    return $this->link;
}

So the connection will be made only once per instance and in any call from Conectar the same object will be returned. Once done, you can change the method that searches for the last id:

function GetUltimoID(){
    return $this->Conectar()->lastInsertId();
}
  • I was only doubtful about the $this->link, I did not define at any time the link variable, when I put it for the first time with $this it already instance it ?

  • No, that’s done inside the if, when it does not yet exist.

  • Ata, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.