10.4. Displaying Posts

I've written the following code and saved it as public_files/view.php to display the blog posts. Posts are ordered in descending date order so newer posts appear first. The current month's posts are displayed first and links are placed at the bottom of the page to traverse other months.

I can pass a timestamp as a parameter to display various months, just like was done in the calendar application in Chapter 5. If the requested month isn't within reason or if the parameters weren't provided, the current month and year are assumed. The script can then determine whichever information it needs from the timestamp using PHP's date() function.

$timestamp = (isset($_GET['t'])) ? $_GET['t'] : time();
list($day, $year) = explode('/', date('m/Y', $timestamp));

After displaying the contents of the month's posts, previous and next links can be generated to traverse to other months. Again, as in Chapter 5, the timestamp can be easily be modified using strtotime(). Although you don't want to provide links beyond the oldest and newest dates, you should check the dates of the oldest and newest entries stored in the database.

$query = sprintf('SELECT UNIX_TIMESTAMP(POST_DATE) AS POST_DATE ' . 'FROM %sBLOG_POST ORDER BY POST_DATE DESC', DB_TBL_PREFIX); $result = mysql_query($query, $GLOBALS['DB']); if (mysql_num_rows($result)) { // determine date of newest post $row = mysql_fetch_assoc($result); $newest = $row['POST_DATE']; // determine date of oldest post mysql_data_seek($result, ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.