سؤال

I am unable to get the lastInserId using PDO in php

$conn = new Db();
$query = "INSERT INTO orders SET
    order_timestamp= :orderTimestamp ,
    customer_id= :customerId";                      
$stmt = $conn->dbConnect()->prepare($query);
$stmt->bindParam(':orderTimestamp', date("Y-m-d H:i:s"), PDO::PARAM_STR);
$stmt->bindParam(':customerId', $_SESSION["customerId"], PDO::PARAM_INT);
$stmt->execute();
$orderId = $conn->lastInsertId();
return $orderId;

Below is the code used for DB Connection

public function dbConnect(){
try {
        $conn = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME, DBUSER, DBPASSWORD);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } 
    catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }   
    return $conn;
}

I am getting an error as mentioned below.

Strict Standards: Only variables should be passed by reference in H:\xampp\htdocs\php\tuf4\hunger\includes\classes\class.hunger.php on line 31

Fatal error: Call to undefined method Db::lastInsertId() in H:\xampp\htdocs\php\tuf4\hunger\includes\classes\class.hunger.php on line 34

هل كانت مفيدة؟

المحلول

bindParam expects a variable, to be passed by reference. date("Y-m-d H:i:s") is clearly not a variable ;)

Try bindValue instead.

Using the correct function will stop the domino effect of errors, and allow you to get the lastInsertId you are seeking.

EDIT: On further review, you are trying to call lastInsertId on your Db wrapper class, not on the PDO object. Try:

$pdo = $conn->dbConnect();
$stmt = $pdo->prepare($query);
// ...
$orderId = $pdo->lastInsertId();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top