Latest rows

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dwfait
Forum Contributor
Posts: 113
Joined: Sun Aug 01, 2004 10:36 pm

Latest rows

Post by dwfait »

Hi. Im making a simple news posting system, but im stuck on one thing. How would i make it display the latest 5 (or any other user specified number) posts from a database?
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Include a timestamp within the database on insertion.
Then use SELECT x from y ORDER BY timestamp DESC LIMIT 5
dwfait
Forum Contributor
Posts: 113
Joined: Sun Aug 01, 2004 10:36 pm

Post by dwfait »

im giving each news item a unique ID, which is auto-incrementated, so should i use that?

Also, how would i get the different fields for each result?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

SELECT * FROM your_table_name ORDER BY `ID` DESC LIMIT 5
where "your_table_name" is your table name, and ID is your unique id field name. That should handle it.
dwfait
Forum Contributor
Posts: 113
Joined: Sun Aug 01, 2004 10:36 pm

Post by dwfait »

Thanks. Then how would i get the different fields from each of the results consecutivly?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

all fields of the row are returned from my query.. you can use [php_man]mysql_fetch_assoc[/php_man]() to retrieve each row in a while loop like so:

Code: Select all

<?php

$query = mysql_query('SELECT * FROM your_table_name ORDER BY `ID` DESC LIMIT 5') or die(mysql_error());

while($row = mysql_fetch_assoc($query))
{
  print_r($row);
}

?>
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

http://www.php.net/mysql

There is good code samples and more functions there.
dwfait
Forum Contributor
Posts: 113
Joined: Sun Aug 01, 2004 10:36 pm

Post by dwfait »

How would i get those variables out of the array and into strings?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

$row['field_name']
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

Post Reply