How To Get the Last ID Assigned by MySQL

Q

How To Get the Last ID Assigned by MySQL? - MySQL FAQs - Managing Tables and Running Queries with PHP Scripts

✍: FYIcenter.com

A

If you use an ID column with AUTO_INCREMENT attribute, you can use the mysql_insert_id() function to get the last ID value assigned by the MySQL server, as shown in the sample script below:

<?php
  include "mysql_connection.php";

  $sql = "INSERT INTO fyi_users (name)" 
     . " VALUES ('John King')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
    print("Last ID inserted: ".mysql_insert_id()."\n");
  } else {
    print("SQL statement failed.\n");
  }

  mysql_close($con); 
?>

If you run this script, you will get something like this:

1 rows inserted.
Last ID inserted: 3

2007-05-11, 6103👍, 0💬