Viewing older news...

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
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Viewing older news...

Post by tito85 »

Hi,

I have this code to display the latest 5 news in my index page. How can i make a link at the end of the news to view older news?

Any help please?

Code: Select all

<?php
  $select = "SELECT * FROM news ORDER BY PostDateTime DESC LIMIT 0,5";
  $result = mysql_query($select);
  while ($news = mysql_fetch_array($result)) {
      echo "<div style=\"overflow: auto;\">";
      echo "<hr style=\"border: 1px solid #06C\" />";
      echo "<h3>" . stripslashes($news['Title']) . "</h3>";
      echo "<small>posted on: " . date("d/m/Y H:i", strtotime($news['PostDateTime'])) . "</small>";
      echo "<p>" . stripslashes(nl2br($news['Body'])) . "</p>";
      echo "<hr style=\"border: 1px solid #06C\" />";
      if (isset($_SESSION['user']) && $_SESSION['superadmin'] == true) {
          echo "<div style=\"float: right;\"><a href=\"editnews.php?id=" . $news['NewsID'] . "\">Edit</a> | <a onclick=\"return confirm('Are you sure you want to delete this news?');\" href=\"deletenews.php?id=" . $news['NewsID'] . "\">Delete</a></div>";
      }
      echo "</div>";
  }
?>
jraede
Forum Contributor
Posts: 254
Joined: Tue Feb 16, 2010 5:39 pm

Re: Viewing older news...

Post by jraede »

Make another page and modify the query with "LIMIT 5, 5". You could take a page value from a URL query in order to change the limit as well, so if you're on page 3 you would want "LIMIT 10, 5", etc.
tito85
Forum Contributor
Posts: 104
Joined: Sat Mar 13, 2010 11:26 am

Re: Viewing older news...

Post by tito85 »

yes but i would like to still be in the index page.

What I would like to do is facebook type... click the button to see older posts...
User avatar
mecha_godzilla
Forum Contributor
Posts: 375
Joined: Wed Apr 14, 2010 4:45 pm
Location: UK

Re: Viewing older news...

Post by mecha_godzilla »

I think you could use OFFSET in your query, though this has some performance issues if you start trying to 'offset' from large numbers (I think adding an ORDER BY clause would help, otherwise MySQL presumably just has to wade its way through x amount of rows until it knows where to start from.)

The main use of LIMIT and OFFSET is to generate the kind of "Now showing results x of x" pagination you get with search engines. The following tutorial shows write to write a script that does this and might be what you're looking for:

http://www.php-mysql-tutorial.com/wikis ... g-php.aspx

If you want to use the same script to either show new or old posts you need to send a $_GET[] value back to the script (so this part of the script is recursive in that respect).

HTH,

Mecha Godzilla
Post Reply