PHP MySQL get last row of a table in database
PHP MySQL get last row of a table in database
If you have auto_increment field set for MySQL table then it is very easy to get details of last row in that table. I have also provided complete php code on how to get details of last n rows in a MySQL table.
First step is, Connect to your database using PHP. Name the file as connect.php
<?php //change these values accordingly $host = "localhost"; $username = "root"; $password = "SOMEPWD"; $database = "MY_DATASE"; //Make your connection to database $con = mysql_connect($host,$username,$password); //Check your connection if (!$con) { die("Could not connect: " . mysql_error()); } //Select your database $db_selected = mysql_select_db($database, $con); //Check your connection if (!$con) { die("Could not connect: " . mysql_error()); } ?>
Second step is to run MySQL query and get the last row in the table. Name this file as last_row.php
include('connect.php'); $table = "MY_TABLE"; $lastrow = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 1"); $get_last_row = mysql_fetch_array($lastrow); echo $get_last_row['Email_Address'];
In the above code we are initially connecting to the database using the include statement.
SELECT * FROM $table ORDER BY id DESC LIMIT 1
This query will return last row from the table. I have many columns in that table and one of them is named as ‘Email_Address’.
After fetching details of the row we can display it using below code.
$get_last_row = mysql_fetch_array($lastrow); echo $get_last_row['Email_Address'];
To get last n rows in a MySQL table, All you have to do is change the MySQL query
SELECT * FROM SOMETABLE ORDER BY id DESC LIMIT 3
I have given numeric 3 after LIMIT. That means sql will display last 3 rows in the table. You can change that number according to your needs. In order to display these values in php you need to modify the code and add a while loop.
$lastrow = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 3");; while($get_last_row = mysql_fetch_array($lastrow)) { echo $get_last_row['Email_Address']."<p>"; }PHP MySQL get last row of a table in database,