简体   繁体   中英

lastInsertId - PDO

Hello guys after inserting a record I want to record the last ID of the register, I'm using PDO lastInsertId () and write in a $ _SESSION, but I'm not getting what is missing in my code I have an error message

<?php 
session_start();

define("SERVER", "localhost");
define("BASES", "databases");
define("USER", "userbases");
define("PASS", "******");

class Sql extends PDO {
    private $conn;
    public function __construct(){
            try {
                $this->conn = new PDO("mysql:dbname=".BASES.";host=".SERVER, USER, PASS);
        }catch (Exception $e) {
            echo "Database Error: ".$e->getMessage();
    }
        catch(Exception $e){
                echo "Generic error: ".$e->getMessage();
        }
    }

    public function query($rawQuery, $params = array()){
        $stmt = $this->conn->prepare($rawQuery);
        $this->setParams($stmt, $params);
        $stmt->execute();
        return $stmt;
    }

    public function query($rawQuery, $params = array()){
       $stmt = $this->conn->prepare($rawQuery);
       $this->setParams($stmt, $params);
       $stmt->execute();
       return $this->conn->lastInsertId(); //agreement by @dennisgon
   }

}

/* INSERT */

$query = "INSERT INTO User(Name,Email) VALUES ('Cledson Stefanato','teste@gmal.com');";
$txt = new Sql();
$txt->query($query);

$_SESSION["RECORD"] = $txt->lastInsertId();

echo "Recorded: ".$_SESSION["RECORD"];

?>

Fatal error: Uncaught Error: Call to a member function lastInsertId() on null in /home/xxxx/index.php:24 Stack trace: #0 {main} thrown in /home/xxxx/index.php on line 24

last lastInsertId() is a function on PDO class, the problem is in your class you return prepare function in think the best way is you must return the lastInsertId() in your function query like this

//---------------Conseld I supplemented by using two different classes and functions as I had suggested.

<?php
/*CONNECTION WITH DATABASES*/
define("SERVER", "localhost");
define("BASES", "databases");
define("USER", "userbases");
define("PASS", "******");

/*DATABASE AND FUNCTION CONNECTION CLASS*/
class QueryPDO extends PDO{

    private $conn;
    public function __construct(){
        $this->conn = new PDO("mysql:dbname=".BASES.";host=".SERVER, USER, PASS);
    }
    /*INSERT, UPDATE AND DELETE FUNCTION*/
    public function query($rawQuery, $params = array()){
        $stmt = $this->conn->prepare($rawQuery);
        $stmt->execute();
        return $this->conn->lastInsertId();
    }

}

/*DATABASE AND FUNCTION CONNECTION CLASS*/
class SelectPDO extends PDO{

    private $conn;
    public function __construct(){
        $this->conn = new PDO("mysql:dbname=".BASES.";host=".SERVER, USER, PASS);
    }
    /*LISTAR DADOS*/
    public function query($rawQuery, $params = array()){
        $stmt = $this->conn->prepare($rawQuery);
        $stmt->execute();
        return $stmt;
    }

    public function select($rawQuery, $params = array()):array{
        $stmt = $this->query($rawQuery, $params);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

}

/*INSERT - MAY ALSO USE WITH UPDATE AND DELETE*/
$query = "INSERT INTO User(
                Nome,
                Email
                ) VALUES (
                'Cledson A Stefanato',
                'txt@gmail.com'
                );";
$txt = new QueryPDO();

/*SESSION RECORD, LAST REGISTRATION*/
$_SESSION["RECORD"] = $txt->query($query);
echo "Recorded: ".$_SESSION["RECORD"];


/*LIST*/
$query = "SELECT * FROM Cadastro";
$txt = new SelectPDO();
$result = $txt->select($query);

//echo json_encode($result);
//echo var_dump($result);

foreach ($result as $dados){
?>
<div style="color: red; font-size: 15px">
    <?php
    echo $dados["Nome"]. "<br />";
    echo $dados["Email"]. "<br />";
    ?>
</div>
<?php } ?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM