Last Insert ID is not returning

China☆狼群 提交于 2020-01-14 12:34:07

问题


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


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/11156735/last-insert-id-is-not-returning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!