MySQL: LAST_INSERT_ID() returns 0

前端 未结 6 1537
天涯浪人
天涯浪人 2020-11-30 07:28

I\'ve got this test table:

CREATE TABLE IF NOT EXISTS `test` (
    `id` INT(10) AUTO_INCREMENT,
    PRIMARY KEY (`id         


        
相关标签:
6条回答
  • 2020-11-30 08:00

    The problem seemed to be in MySQL's phpmyadmin config file PersistentConnections set to FALSE which resulted in a new CONNECTION_ID every time a query was issued - therefore rendering SELECT LAST_INSERT_ID() ineffective.

    more info in the subsequent topic Every query creates a new CONNECTION_ID()

    Also thanks dnagirl for help

    0 讨论(0)
  • 2020-11-30 08:12

    you have to combine

    INSERT INTO test (title) VALUES ('test');SELECT LAST_INSERT_ID();
    

    Then you will get the last insert id

    0 讨论(0)
  • 2020-11-30 08:19

    I had the same issue. mysql_insert_id() or LAST_INSERT_ID() returned 0 when requested inside a PHP function with an INSERT query.

    I sorted the issue by requesting the value of mysql_insert_id() from a separate PHP function called right after the function that INSERT query.

    0 讨论(0)
  • 2020-11-30 08:19

    it work perfectly...try it...

        $result = mysql_query("INSERT INTO `test` (`title`) VALUES ('test')");
        if ($result) {
            $id = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM tablename WHERE id = $id") or die(mysql_error());
            // return user details
            if (mysql_num_rows($result) > 0) {
                return mysql_fetch_array($result);
            } else {
                return false;
            }
        } else {
            return false;
        }
    
    0 讨论(0)
  • 2020-11-30 08:21

    Just my 50 cents for this issue, I simply noticed that you won't get a LAST_INSERT_ID greater than 0 if your table has no AUTO_INCREMENT set to an index.

    I wasted about half hour on this. Turns out I keep getting a LAST_INSERT_ID() of 0, which for this table is actually ok.

    0 讨论(0)
  • 2020-11-30 08:24

    I Had the same issues but I have resolved this by creating a transaction.

    $db->begin();
    $sql = "INSERT INTO 'test' VALUES('test')";
    
    if ($db->query($sql))
    {
        $id = $db->last_insert_id('test');
        $db->commit();
        return $id;
    }
    else{
        $db->rollback();
        return -1;
    }
    

    I had tried

    return $db->last_insert_id('test');
    

    after the "commit" but that always returned "0"

    hope that can help you

    0 讨论(0)
提交回复
热议问题