0
I need to get the ID of my last INSERT in the database, however the function lastInsertId() only returns me 0.
This is my class that connects to the bank:
<?php 
namespace App\model;
class ModelConexao{
    
    public function conecta() {
        
        try {
            $pdo = new \PDO("mysql:host=".HOST.";dbname=".DB."","".USER."","".PASS."",array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            return $pdo;
            
        } catch (Exception $e) {
            
            echo "Falha ao tentar conectar-se ao banco de dados. Erro: " . $e->getMessage();
            exit();
        }
    }
}
 ?>
This is my class that inserts the data into the database:
<?php 
namespace App\model;
use App\model\ModelConexao;
class ModelCadastro extends ModelConexao {
    
    public function insert($email, $senha){
        $sql = $this->conecta()->prepare("INSERT INTO LOGIN SET email=:email, senha=:senha");
        $sql->bindParam(":email",$email,\PDO::PARAM_STR);
        $sql->bindParam(":senha",$senha,\PDO::PARAM_STR);
        $sql->execute();
        return $this->conecta()->lastInsertId();
    }
}
 ?>
$this->conecta()->lastInsertId(), why opened a new connection with the bank to pick up the last id?– Woss
So @Woss I figured this might be wrong, but when I make $sql->lastInsertId() it’s giving the following error: "Fatal error: Uncaught Error: Call to Undefined method Pdostatement::lastInsertId() "
– EP Criação
That’s because
$sqlis the return ofprepare, nayconecta.– Woss
I get it. What would that make you? I tried $connected = $this->connects(); Before the prepare and at the end I made $connected->lastInsertId(); which also gave me zero.
– EP Criação
@Woss now I got brother. First I took the connection: $connected = $this->connects(); Then I used this variable to do the "prepare": $connected->prepare... and finally I got the ID: $connected->lastInsertId(); TOPZER!!! Thank you very much meeeesmo. I’m trying to set your answer as valid but I’m not getting.
– EP Criação