PHP get the id of the last data

i am new to php language and i want to add the id of the last data in the database as an int to a variable.
can you help me how can i do this

here are some of my attempts:

$lastID = mysqli_query("SELECT * from posts ORDER BY post_id DESC LIMIT 1");

$lastID = mysqli_query("SELECT * from posts ORDER BY post_id DESC LIMIT 1");
$lastid = (int)$lastID;


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

First of all, use this query.

SELECT MAX(post_id) post_id FROM posts

It’s more efficient than the query in your example, especially if post_id is the primary key.

Second, do this.

$result = mysqli_query($connection, "SELECT MAX(post_id) post_id FROM posts");
if (!$result) { 
   /* the query failed, report an error */
} else {
    $row = mysqli_fetch_object($result);
    $lastID = $row->post_id;
    $lastID += 1;

Third, beware a possible race condition. If another instance of a program inserts something into the table between the time you fetch the MAX(post_id) and the time you use the incremented value, the incremented value may be wrong. This kind of problem is very hard to detect when testing because you have to get the concurrency just right. But it will come up in production when your application is busy.

Method 2

First make sure you’ve connected to the mysql server:

$db_handle = mysqli_connect($db_server_name, $db_user_name, $db_password);

Select the database you want to work with:


write your query. The following query will get you the largest post_id number:

$query = "SELECT post_id FROM posts ORDER BY post_id DESC LIMIT 1";

query mysql:

$result = mysqli_query($db_handle, $query);

Fetch your data as a row array from the query result:

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

put the value of ‘post_id’ from the row array into a variable:

$lastid = $row['post_id'];

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x