0
I’m having trouble getting the last id inserted in my table using the php PDO function lastInsertId()
How do I get the last id inserted in my table using my structure?
Connection to the bank
class ConnectionDB{
private function setConnection(){
try {
$con = new PDO("mysql:host=localhost;dbname=easyjobapi", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->exec("SET NAMES 'utf8'");
return $con;
} catch (PDOException $e) {
echo "Erro ao conectar-se: ".$e->getMessage();
}
}
public function getConnection(){
return $this->setConnection();
}
}
Test file
$con = new ConnectionDB();
/*tabela teste so contem um coluna chamada id AUTO_INCREMENT e a coluna nome*/
$stmt2 = $con->getConnection()->prepare("INSERT INTO teste (nome) VALUES ('MAX123')");
$stmt2->execute();
var_dump($con->lastInsertId());
Error presented
<br />
<b>Fatal error</b>: Uncaught Error: Call to undefined method ConnectionDB::lastInsertId() in C:\xampp\htdocs\easyjob\api\site\teste.php:10
Stack trace:
#0 {main}
thrown in <b>C:\xampp\htdocs\easyjob\api\site\teste.php</b> on line <b>10</b><br />
I’ve tried too:
$lastId = $con->lastInsertId();
var_dump($lastId);
But you still give me the error:
<br />
<b>Fatal error</b>: Uncaught Error: Call to undefined method ConnectionDB::lastInsertId() in C:\xampp\htdocs\easyjob\api\site\teste.php:10
Stack trace:
#0 {main}
thrown in <b>C:\xampp\htdocs\easyjob\api\site\teste.php</b> on line <b>10</b><br />
How to proceed?
The example of this answer is using a Postgres function...
– Max Rogério