Page 1 of 1

Reading the last five entries in database from bottom to top

Posted: Fri Apr 18, 2003 6:41 pm
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.

Posted: Sat Apr 19, 2003 5:20 am
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