How do I get the last inserted ID of a MySQL table in PHP?

后端 未结 16 2286
温柔的废话
温柔的废话 2020-11-21 23:09

I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?

Is it similar to SELECT MAX(id) FROM

相关标签:
16条回答
  • 2020-11-21 23:45

    I prefer use a pure MySQL syntax to get last auto_increment id of the table I want.

    php mysql_insert_id() and mysql last_insert_id() give only last transaction ID.

    If you want last auto_incremented ID of any table in your schema (not only last transaction one), you can use this query

    SELECT AUTO_INCREMENT FROM information_schema.TABLES
        WHERE TABLE_SCHEMA = 'my_database' 
        AND TABLE_NAME = 'my_table_name';
    

    That's it.

    0 讨论(0)
  • 2020-11-21 23:49

    I tried

    mysqli_insert_id($dbConnectionObj)
    

    This returns the current connection's last inserted id, so if you are managing your connections properly this should work. Worked for me at least.

    0 讨论(0)
  • 2020-11-21 23:50

    With PDO:

    $pdo->lastInsertId();
    

    With Mysqli:

    $mysqli->insert_id;
    

    Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

    0 讨论(0)
  • 2020-11-21 23:50

    Clean and Simple -

    $selectquery="SELECT id FROM tableName ORDER BY id DESC LIMIT 1";
    $result = $mysqli->query($selectquery);
    $row = $result->fetch_assoc();
    echo $row['id'];
    
    0 讨论(0)
提交回复
热议问题