SQL get latest record in PHP
Go to solution
Solved by mcrius,
This is my current code:
$query = sprintf("SELECT * FROM invoices WHERE CustomerID = '" . mysql_real_escape_string($customerID) . "';"); $result = mysql_query($query); if (!$result) { die(mysql_error()); } while ($invoice = mysql_fetch_assoc($result)) { $status = $invoice['Status'];Instead of the
SELECT *I would like it to only retrieve the latest record (there is a date column if that is required)
Thanks D14RAP
If it is a MySQL DB, you can use
SELECT * FROM Invoices ORDER BY date_col DESC LIMIT 1;
or you can order by id if the pk is AI. Bear in mind that if the latest invoice for a customer will always have the largest primary key value you should order by that. The date column will have to be indexed to achieve the same performance as with a PK in a table with a lot of rows.
Pretty much every DB server has a way to do it. In Oracle you would use a rownum for example. Hope this helps.

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now