Difficulties with PHP - lastInsertId () [duplicate]

0

I'm having trouble getting the last id inserted in my table using the php function PDO 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 Displayed

<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 it too:

$lastId = $con->lastInsertId();
var_dump($lastId);

But I still get 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?

    
asked by anonymous 10.11.2017 / 00:59

1 answer

0

dude I think your connection class may be wrong try this

  

connection

<?php
class ConnectionDB{
private $conn;  
public function __construct(){
try {
     $con = new PDO("mysql:host=localhost;dbname=easyjobapi", "root", "");
     $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $con->exec("SET NAMES 'utf8'");
     $this->conn = $con;

   } catch (PDOException $e) {
     echo "Erro ao conectar-se: ".$e->getMessage();
   }
 }
 public function getConnection(){
 return $this->conn;
 }

}

  

test

  $con = new ConnectionDB();
  /*tabela teste so contem um coluna chamada id AUTO_INCREMENT e a coluna nome*/
  $stmt2 = $con->getConnection();
  $stmt2->prepare("INSERT INTO teste (nome) VALUES ('MAX123')");
  $stmt2->execute();
  $las_id = $stmt2->lastInsertId();
  $id = var_dump($las_id);
    
10.11.2017 / 01:06