MySQL Driven Monthly Archiving

Here we take articles from a MySQL database and organize them into seperate months. It starts one month previous from current month. so if it is April this will start organizing articles from March back.

This script shows how powerful MySQL SQL calls can be and eliminates a lot of the PHP, which helps speed up page parse times. You must have a date created field in your table and I use DATETIME stamps.

function article_toc(){
 
    $content = '< div class="catalog_page_content_row"> < p class="accessory_details">';
 
 
 
    $sql_m = "SELECT distinct monthname(date_created) AS month, year(date_created) AS year from blog WHERE date_created < DATE_FORMAT(CURDATE(), '%Y-%m-01') ORDER BY date_created DESC";
    // remove WHERE syntax for all months including current month
    $m_rs =mysql_query($sql_m) or die("Error: ".mysql_error());
 
 
    while($months_rs = mysql_fetch_assoc($m_rs)){
 
        /* MySQL does this for me! *********************************************
        $month_date = date('m', strtotime("this ".$months_rs['month']))+1;
        $month_name = $months[intval($month_date)];
        #########################################################################*/
 
        $content .= '< span class="cart_item_ul2">< b>'.$months_rs['month'].' '.$months_rs['year'].'< br />';
 
        //get information from database
        $sql = 'SELECT title, link, date_created FROM blog ORDER BY date_created DESC';
        $rs= mysql_query($sql) or die("Error on Line 210: ".mysql_error());
 
            while($article_rs = mysql_fetch_assoc($rs)){
 
                // this allows us to build our if statement
                $date_created = substr($article_rs['date_created'], 0, 10); // gets the date from DATETIME stamp
 
                $ds = explode('-', $date_created);
 
                //assign month and year to a meaningful variable
                $article_month = date('F', mktime(0, 0, 0, $ds[1], $ds[2], $ds[0]));
                $article_year = $ds[0];
 
 
                //if month and year in database == to current month loop output it
                if($article_month == $months_rs['month'] && $article_year == $months_rs['year']){
                    $content .= '< a href ="'.$article_rs['link'].'">'.$article_rs['title'].'< /a>< br />';
                }
            } // while
 
        }
 
 
    $content .= '< /p>
                 < /div>';
    return $content;
 
}//function

Now we call the function

echo article_toc();
 
development/php/mysql_archive.txt · Last modified: 2007/09/14 13:47 by vincenzobar
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki