0

this is the database file that has db connections it is called db.php

<?php   
class Database
{
    private $dsn = "mysql:host=localhost;dbname=testmovie";
    private $user = "root";
    private $pass = "";
    public $conn;

    function __construct()
    {
        try {
        $this->conn = new PDO($this->dsn,$this->user,$this->pass);
        } catch (\Exception $e) {
        echo $e->getMessage();
        }
    }

function to insert details and return lastInsertId

    public function booking($fname,$lname,$tseats,$show_id,$email,$phone,$price)
    {
        $sql ="INSERT INTO bookings
                    (firstname,lastname,seats_booked,show_id,email,phone,price) 
                VALUES (:fname, :lname, :tseats, :show_id, :email, 
                        :phone, :price)";
        $stmt= $this->conn->prepare($sql);
        $stmt->execute(['fname'=>$fname, 'lname'=>$lname, 
                        'tseats'=>$tseats, 'show_id'=>$show_id, 
                        'email'=>$email, 'phone'=>$phone, 
                        'price'=>$price]);
        $last= $stmt->lastInsertId();
        return $last;
    }
}
?>

A new php file that prints value of the last id entered

<?php 
require_once 'db.php';
$db= new Database();

the variable are fetched form input fields.

if ($last=$db->booking($fname,$lname,$tseats,$show_id,$email,$phone,$price)) {
    echo $last;
}
?>
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • 1
    Change `$stmt->lastInsertId();` to `$this->conn->lastInsertId();` The method `lastInsertId()` is a method on the PDO instance, not the statement: https://www.php.net/manual/en/pdo.lastinsertid.php – M. Eriksson Dec 14 '21 at 17:14
  • Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Dec 14 '21 at 17:16
  • 1
    Does this answer your question? [How to get last inserted id?](https://stackoverflow.com/questions/5228780/how-to-get-last-inserted-id) – Mostafa Ezzat Dec 14 '21 at 17:31

0 Answers0