How to fetch the last ID from a MySQL Table and save it in a PHP Variable

When you are Involved in comparing and updating two different tables there may be times when you would need the last ID of a table so that it can be used in another table provided the ID is a primary key set to Auto Increment.

The way you would go about this is to use the max keyword to get the last ID of a table and then use the mysql_fetch_row function to fetch a row of data from the result handle. This value is then saved in a PHP Variable that can be later used for further manipulation. The overall code would appear to be something like this-

//Database Connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);



//Get the Last ID of a table. The column name is "SNo"
$last_id = mysqli_query($db,"SELECT max(SNo) FROM Test4_HarvestData");




if (!$last_id) {

    die('Could not query:' . mysql_error());

}



//The Last ID saved in a PHP Variable
$row_sno= mysqli_fetch_row($last_id);


echo "<br>The Last ID is : ".$row_sno[0];

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s