Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last Insert ID is not returning

Tags:

php

mysql

pdo

I have following code for inserting data into database using PDO.

It inserts data into database but not return last inserted in ID.

here userid is primary key

  try {
        $dbh = new PDO('mysql:host=localhost;dbname=crud_demo', "username", "password");

        $sqlQuery = "INSERT INTO users(userid,first_name,last_name,email,password)
            VALUES(:userid,:first_name,:last_name,:email,:password)";

        $statement = $dbh->prepare($sqlQuery);
        $bind = array(
            ":userid" => "bhavik",
            ":first_name" => "Bhavik",
            ":last_name" => "Patel",
            ":email" => "[email protected]",
            ":password" => "1234567"
        );
        $statement->execute($bind);
        echo $dbh->lastInsertId();
    } catch (PDOException $e) {
        echo $e->getMessage();
    }

$dbh->lastInsertId(); always return 0 whatever i insert value for userid

like image 982
Chetan Patel Avatar asked Dec 06 '22 13:12

Chetan Patel


1 Answers

lastInsertId() only returns IDs automatically generated in an AUTO_INCREMENT column. Your PRIMARY KEY is apparently a string (or at least you're inserting a string in it). Since you're inserting a known value, you don't actually need to find out the inserted ID — you've specified it yourself.

like image 108
lanzz Avatar answered Dec 10 '22 11:12

lanzz