4

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" => "bhavitk@live.in",
            ":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

Chetan Patel
  • 183
  • 2
  • 10

3 Answers3

10

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.

lanzz
  • 42,060
  • 10
  • 89
  • 98
  • 1
    +1. `lastInsertId()` accept a `$name` parameter. Is it possible to specify `userid` if it's an integer type ? (Never tried, just thought about it) – zessx Jun 22 '12 at 13:15
  • 1
    `lastInsertId($name)` is used for databases like Postgresql. There is no `AUTO_INCREMENT` column modifier there, but you have sequences that implement this functionality, and as a side effect you can have multiple incremental values in the table, and you need to provide the name of the sequence whose last value you want. – lanzz Jun 22 '12 at 13:17
5

The userid doesn't have an auto_increment attribute in your database, so lastInsertId() will never return anything useful.

You can only lastInsertId() if your field is:

  1. the primary key
  2. not null
  3. an integer type (int, bigint, etc.)
  4. auto_increment
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

first you need to check insert query.

if its run proper then use mysql function like mysql_insert_id().

if this function is run property then may be possible to mistake in your $dbh->lastInsertId()

this function.

  • Asker is using the PDO_MySQL extension, not ext/mysql. ext/mysql is [not recommended](http://us3.php.net/manual/en/mysqlinfo.api.choosing.php) for future development. And, [`lastInsertId()`](http://us.php.net/manual/en/pdo.lastinsertid.php) is part of the PDO library, not a user-defined method. – Wiseguy Jun 22 '12 at 13:23