简体   繁体   中英

How to get the last ID got inserted into Database Table?

I'm building a magazine management system. I've made archive for magazines using sql db table and php. I want to show the latest magazine data on the home page by getting the last auto incremented id from the archive table from db. But how? I'm Using SQL, not PDO

The easiest way to get what you want is probably the following:

SELECT *
FROM magazines
ORDER BY id DESC
LIMIT 1

But you might want to consider creating a date entered column to use instead of the auto increment ID.

order by is easy way and if you only 1 record then use limit

select * from magazines order by id desc limit 1;

you can use mysql max function

select max(id) as ID from magazines;

and if you want to get last insert id in insert query then use this

 $last_id = $conn->insert_id; // mysqli

 $last_id = mysql_insert_id(); // mysql but remove from php 7

 $lastId = $dbh->lastInsertId(); // pdo

If you're using PDO, use PDO::lastInsertId.

If you're using Mysqli, use mysqli::$insert_id.

If you're still using Mysql:mysql_insert_id.

The Query should be

SELECT max(ID) from magazine

This will return the maximum and the most recent id. You can then pass this query to desired PHP API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM