Why is mysqli_insert_id() always returning 0?

前端 未结 4 1909
醉话见心
醉话见心 2020-12-01 14:37

I have the following code. The mysqli_insert_id() (in this case \"$last_row\"), which is supposed to return the last row of the table, is always returning 0. Why is it so?

相关标签:
4条回答
  • 2020-12-01 14:54

    Another gotcha with this function -- if you're doing:

    INSERT INTO table (col1, col2) VALUES (1, 2) ON DUPLICATE KEY UPDATE col2=3
    

    and insert doesn't happen because of a duplicate key and for the UPDATE, like in my case, if col2 was already set to 3, then mysqli_insert_id will also return 0.

    0 讨论(0)
  • 2020-12-01 14:59

    mysqli_insert_id does not return the ID of the last row of the table. From the docs, it:

    ...returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

    (My emphasis)

    That is, if you were to run it immediately after an insert that auto-generated an ID, on the same connection you did the insert with, it would return the ID generated for that insert.

    This is illustrated by the example in the docs linked above:

    $query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
    $mysqli->query($query);
    
    printf ("New Record has id %d.\n", $mysqli->insert_id);
    
    0 讨论(0)
  • 2020-12-01 15:11

    To get the result, you should place the

    $last_row = mysqli_insert_id($connection);
    

    after your INSERT query

    0 讨论(0)
  • 2020-12-01 15:16

    For other people coming here, maybe you tried INSERT IGNORE INTO and you have a UNIQUE value that was already inserted. In that case, this id is zero.

    Also you'll get "zero" if MySQL runs out of connections. I'm no expert on persistent connections but this might help somebody?

    As you probably know PHP “mysql” extension supported persistent connections but they were disabled in new “mysqli” extension --Peter Zaitsev

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