Jump to content

Archived

This topic is now archived and is closed to further replies.

wipe

Last 5 entries with php and mysql

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

Share this post


Link to post
Share on other sites
SELECT * FROM table ORDER BY date DESC ?

Share this post


Link to post
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)

Share this post


Link to post
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. 

Share this post


Link to post
Share on other sites
you would need to loop over all the tables in turn, to get the last 5 out
[code]select * from table where date = 'daet here' limit 5[/code]

Share this post


Link to post
Share on other sites
An added comment from the above example union will only work if the same information is in all table fields.

that what union does just joins all table fields as one.

lol...................... sorry

Share this post


Link to post
Share on other sites

×

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.