Reading the last five entries in database from bottom to top

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
Trip1
Forum Newbie
Posts: 23
Joined: Sat Jan 25, 2003 7:36 pm

Reading the last five entries in database from bottom to top

Post by Trip1 »

I have a database called main_news with three fields: Subject, Text and an auto-incrementing field called newsid.

I want to read out the last five news posts from bottom to top, so if i post something it comes out first and the other 4 below it. I want the subject to come out first and in bold, then a <br> and then the text of the news, then a <br> then the next subject etc.

I have been stuck on figuring out how exactly to do this.. any help is appreciated, thanks in advance.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

When you do your SQL statement use LIMIT and ORDER BY, so your code would look something like:

Code: Select all

SELECT newsid, Subject, Text FROM main_news ORDER BY newsid DESC LIMIT 5
Check out:
http://www.mysql.com/doc/en/SELECT.html

Then you just need to loop through the results to do the HTML formatting, something like:

Code: Select all

<?php
$num_results = 5;
$sql = "SELECT newsid, Subject, Text FROM main_news ORDER BY newsid DESC LIMIT $num_results";
$result = mysql_query($sql) or die(mysql_error().'<p>'.$sql.'</p>');

while ($row = mysql_fetch_assoc($result)) {
    $subject = htmlspecialchars(stripslashes($row['Subject']));
    $text = nl2br(htmlspecialchars(stripslashes($row['Text'])));
    echo '<h1>'.$subject.'</h1>';
    echo '<p>'.$text.'</p>';
}
?>
Mac
Post Reply