Sorting blog entries by date

For a project I was doing I needed to organize some dated entries into what month & year they were publised. Here's how I did it.


$conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_DATABASE);
if( mysqli_connect_errno() ) { die("Cannot connect to the database."); }
$conn->query("SET NAMES utf8 COLLATE utf8_danish_ci");

$oldmonth = ''; $month = '';
$oldyear = ''; $year = '';

$site_content = '<ul>';
$query = "SELECT *,DATE_FORMAT(publish_date, '%Y-%m-%d') as date FROM " . DB_TABLE . " WHERE published IS TRUE ORDER BY publish_date DESC";
            $result = $conn->query($query);

            if ( $result->num_rows == 0 )
{ $site_content = ''; } else { $site_content = '
'; } while ( $row = $result->fetch_object() ) {
if ( !isset( $year ) ) { $change = 1; } else { $oldyear = $year; $oldmonth = $month; } $period = getdate(strtotime($row->date)); $year = $period['year']; $month = $period['month']; setlocale(LC_TIME, "no_NO"); $month = ucfirst(strftime('%B', strtotime($row->date))); if ( $oldmonth != $month || $oldyear != $year ) { $change = 1; $site_content .= "\n\n"; } if ( $change == 1 ) { $site_content .= "$month $year"; $change = 0; $site_content .= "\n\n