Jump to content

News Archive Question


broomstick

Recommended Posts

Say I have a simple News Management system, it collects the title of the story, the name of the author, the body text, an image and the date it was posted (in YYYY-MM-DD format).

 

How would I go about dynamically creating archive links based on the dates found in the database?

 

Ideally I'd like it to look something like this:

 

2007

January

February

... and on ...

November

December

2008

January

February

March

 

Each month would generate a link including the year and month to which it refers (something like news_archive.php?year=2007&month=01, or however it'd be formatted).

 

I understand PHP to an extent (like I can pull stuff from databases, do the CRUD thing, etc.), but I'm kind of lost on this.

Link to comment
https://forums.phpfreaks.com/topic/99219-news-archive-question/
Share on other sites

  • 7 months later...

This is sort of complicated but I will give it a shot.

 

<?php
function createArchiveLinks($author) {
$sql = "SELECT `date` FROM news WHERE author = '" . $author . "' ORDER BY `date`";
$query = mysql_query($sql);

while ($row = mysql_fetch_assoc($query)) {
	$year = date("Y", $row['date']);
	$month = date("m", $row['date']);
	$month_full = date("F", $row['date']);
	$y_m_new = $month . $year;

	if ($y_m_new != $y_m_old) {
		$return[$x]['full_date'] = $month_full . '-' . $year;					
		$return[$x]['url'] = '<a href="' .SERVER_URL. '/news_archive.php?year=' . $year . '&month=' . $month . '">'.$month_full ." ". $year .'</a>';
		$return[$x]['month'] = $month_full;
		$return[$x]['year'] = $year;
		$y_m_old = $month.$year;	
		$x++;					
	}
}
}

$archive_links = createArchiveLinks('author'); // grab links for user 'author'

foreach ($archive_links as $key => $val) {
echo $val['url'] . "<br />";
}
?>

 

Not tested and the return array contains probably more information than needed but you can manipulate it how you want. This assumes SERVER_URL is a defined constant, you want it for a user, you have a SQL connection and your date field is called `date` and your table is called news.

 

I am sure you can manipulate this to your needs...this is untested.

Link to comment
https://forums.phpfreaks.com/topic/99219-news-archive-question/#findComment-689041
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.