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

后端 未结 16 2300
温柔的废话
温柔的废话 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:28

    It's sad not to see any answers with an example.

    Using Mysqli::$insert_id:

    $sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
    $mysqli->query($sql);
    $last_inserted_id=$mysqli->insert_id; // returns last ID
    

    Using PDO::lastInsertId:

    $sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
    $database->query($sql);
    $last_inserted_id=$database->lastInsertId(); // returns last ID
    
    0 讨论(0)
  • 2020-11-21 23:29

    Try this should work fine:

    $link = mysqli_connect("localhost", "my_user", "my_password", "world");
    
    $query = "INSERT blah blah blah...";
    $result = mysqli_query($link, $query);
    
    echo mysqli_insert_id($link);
    
    0 讨论(0)
  • 2020-11-21 23:31

    It's ok. Also you can use LAST_INSERT_ID()

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

    What you wrote would get you the greatest id assuming they were unique and auto-incremented that would be fine assuming you are okay with inviting concurrency issues.
    Since you're using MySQL as your database, there is the specific function LAST_INSERT_ID() which only works on the current connection that did the insert.
    PHP offers a specific function for that too called mysql_insert_id.

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

    Use mysqli as mysql is depricating

    <?php
    $mysqli = new mysqli("localhost", "yourUsername", "yourPassword", "yourDB");
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    // Conside employee table with id,name,designation
    $query = "INSERT INTO myCity VALUES (NULL, 'Ram', 'Developer')";
    $mysqli->query($query);
    
    printf ("New Record has id %d.\n", $mysqli->insert_id);
    
    /* close connection */
    $mysqli->close();
    ?>
    
    0 讨论(0)
  • 2020-11-21 23:41

    there is a function to know what was the last id inserted in the current connection

    mysql_query('INSERT INTO FOO(a) VALUES(\'b\')');
    $id = mysql_insert_id();
    

    plus using max is a bad idea because it could lead to problems if your code is used at same time in two different sessions.

    That function is called mysql_insert_id

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