How can I retrieve the last record from a database using PHP?
To retrieve the last record from a database using PHP, you can use an SQL query with the ORDER BY clause to sort the records in descending order based on a unique identifier (such as an auto-incremented ID) and then limit the result to 1. This will fetch the last record in the database.
<?php
// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Retrieve the last record from the database
$query = "SELECT * FROM table_name ORDER BY id DESC LIMIT 1";
$result = $connection->query($query);
// Fetch the last record
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
// Process the last record here
} else {
echo "No records found";
}
// Close the connection
$connection->close();
?>
Keywords
Related Questions
- What are the advantages of using mysqli or PDO extensions over the deprecated mysql extension in PHP for database operations?
- What are some best practices for handling MySQL queries and result sets in PHP to avoid issues like the one described in the forum thread?
- Are there any specific best practices or guidelines for handling form submissions and data storage in PHP and Smarty?