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

2018-12-31 02:42发布

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 table?

标签: php mysql
22条回答
春风洒进眼中
2楼-- · 2018-12-31 03:26

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.

查看更多
有味是清欢
3楼-- · 2018-12-31 03:28

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);
查看更多
与君花间醉酒
4楼-- · 2018-12-31 03:30

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

查看更多
春风洒进眼中
5楼-- · 2018-12-31 03:30

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
查看更多
大哥的爱人
6楼-- · 2018-12-31 03:31

You can get the latest inserted id by the in built php function mysql_insert_id();

$id = mysql_insert_id();

you an also get the latest id by

$id = last_insert_id();
查看更多
步步皆殇っ
7楼-- · 2018-12-31 03:31

If your table have AUTO INCREMENT column like UserID,Emp_ID,.. then you can use this query to get last inserted record SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name) In PHP code:

$con = mysqli_connect('localhost', 'userid', 'password', 'database_name');
                                if (!$con) {
                                    die('Could not connect: ' . mysqli_error($con));
                                }
                                $sql = "SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)";
                                $result = mysqli_query($con, $sql);

Then you can use fetched data as your requirement

查看更多
登录 后发表回答