Search code examples
phplast-insert-id

How to use lastInsertId in this case?


What I want is to get and store the last inserted ID, but I am not sure how. The scenario is, after a user add a record he/she will be redirected to a page that will show him/her of the summary of what he/she saved. But I am not sure how I can do that, to retrieved the recently added record. I have a class which look like this record.php

<?php
class Record {
     private $conn;
     private $table_name_1 = "name_of_the_table_1";
     private $table_name_2 = "name_of_the_table_2";

     public $name;
     public $age;
     public function __construct($db){
    $this->conn = $db;
}
function newRecord(){
     $query = "INSERT INTO " . $this->table_name_1 . " SET name=:name;
     INSERT INTO " . $this->table_name_2 . " SET age=:age";
     $stmt = $this->conn->prepare($query);
     $this->name=$this->name;
     $this->age=$this->age;
     $stmt->bindParam(':name', $this->name);
     $stmt->bindParam(':age', $this->age);
     if($stmt->execute()){
        return  true;
    }else{
        return false;
    }
   }
   }
  ?>

now I have another php form that create and add record, the code is something like this add_record.php

<?php
inlude_once 'db.php'
inlude_once 'record.php'

$database = new Database();
$db = $database->getConnection();

$record = new Record($db);
?>

<?php 
if($_POST) {
$record->name=$_POST['name'];
$record->age=$_POST['age'];

if(record->record()){
header("Location:{$home_url}view_recently_added_record.php?action=record_saved");
}
else{
echo "Unable to save";
}
}
?>

The idea is to save the query to two different table and the same time automatically record the auto increment ID of table 1 to table 2 so that they have a relationship. I am thinking I can do that if I can store immediately the ID from table 1 and assigned it a variable maybe so it can be automatically saved to table two using a new query or function maybe. Is this possible? does it make sense? and another thing I wanted to display the recently recorded data immediately to the user. Thank you.


Solution

  • You can return $stmt->insert_id or -1 insteaf of boolean in the newRecord function:

    function newRecord(){
         ...
         if($stmt->execute()){
            return $stmt->insert_id;
        }else{
            return -1;
        }
       }
    

    and use the value to redirect like this:

    $newrecord = record->newRecord();
    if($newrecord != -1) {
       header("Location:{$home_url}view_recently_added_record.php?action=record_saved&id=".$newrecord);
    }
    else{
       echo "Unable to save";
    }