When we pull a value from MySQL or another database, there's nothing stopping us from pullingÂ the sameÂ value in different ways within the same query.
For instance, say we want to pull dates in their raw format, which is suitable for sorting but may not be the most usefulÂ formatting for display.Â We might find a format like "Jan-13-2009 Â· Wed"Â more useful for display purposes, though it's useless for sorting on.
We could massage the data in PHP to alter the date format, but it would be much faster and more efficient to let the database server deal with that.Â You'll also have cleaner PHP code if you deliver attributes from your database server ready to use.
Here's an example of a query that pulls all values (the asterisk) followed by additional formats of two dates.Â Note that the additional formats are manipulations of data which have already been pulled in their raw format by the asterisk in the select statement.Â Note also that I've adopted the convention ofÂ prepending "
fmt_" to these derived attributes.
1 2 3 4 5
SELECT *, DATE_FORMAT(date_received,'%Y-%b-%d Â· %a') AS fmt_date_received, DATE_FORMAT(date_dispatched,'%Y-%b-%d Â· %a') AS fmt_date_dispatched, FROM packages
You're now free to use
fmt_date_received independently throughout your code.