Jump to content

Last 5 entries with php and mysql


wipe

Recommended Posts

Hi guys,

i have a small question.

Im using a script that display all results in a DB and i can do some query.
i insert also date.

Now i need to know how can i display with a echo the last 5 posts into my DB using date. How can i do that?

Regards,
Wipe
Link to comment
Share on other sites

[quote author=birdie link=topic=99352.msg391228#msg391228 date=1151966212]
SELECT * FROM table ORDER BY date DESC ?
[/quote]

Wouldn't this just show the last five entry's for the "table".
How would you do this for your whole database?
(check all your tables)
Link to comment
Share on other sites

I honestly don't know if there is a more efficient way than this (if there is, [b]Barand[/b] would know :) ), but here's my solution:

let's say you have 3 tables called

table1
table2
table3

and in each table is date column. it doesn't matter if they are all named the same or not, as long as they are the same data type.  but let's just say for the sake of clarity they are all named different:

date1
date2
date3

and we want to choose the 5 most recent dates out of all 3 tables overall, right? okay so here we go:

[b](SELECT date1 FROM table1) UNION (SELECT date2 FROM table2) UNION (SELECT date3 FROM table3) ORDER BY date1 DESC LIMIT 5[/b]

okay so here's an explanation of what this does: this runs 3 seperate queries all at once.  Then it merges all the data into one column.  The column is named the same name as what is selected in the first query so since that is date1, the result will return your list with the column named date1.  That is why we are ordering by date1 at the end. 
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.