PHP/MySQL - Ordering a database table by year and month separately. - php

I'm trying to build a HTML table from a list of newsletters in a MySQL database.
It's currently ordered by descending order, and outputting as below:
https://jsfiddle.net/e8zrLjqu/
As you will see the years are in the right place, but the months of the newsletters need to be in ascending order, while keeping the years in descending order, so that each newsletter matches up with the table heading....like this example:
Do I somehow need to use DATE_FORMAT to separate the ordering? The date in the database is formatted like this: 2014-07-01
Php:
$category_data_fields = '`id`';
$category_where_conditions = '`publish` = \'y\' and `fund_id` = ' . $this_fund_id . ' and `category_status` = \'n\'';
$category_result = $db->selectByStrings($category_data_fields, '`category`', $category_where_conditions, '`position`');
$resource_data_fields = '`id`, `date`, `heading`, `file`';
$heading_investor_newsletter = $lang_row['name'] . ' Investor Newsletters';
$copy_investor_newsletter = $tab0 . $lang_row['investor_news_copy'] . $retn . $retn;
$note = $tab1 . $lang_row['investor_news_note'] . $retn . $retn;
if ($db->getNumRows($category_result) > 0) {
$cat_data = $db->getNextRow($category_result);
/*
* list selectable years
*/
$resource_where_conditions = '`publish` = \'y\' and `category_id` = ' . $cat_data['id'];
$date_result = $db->selectByStrings($resource_data_fields, '`resource`', $resource_where_conditions, '`date` desc');
$current_year = '';
$base_url_query = (_USE_SEO_URLS === true) ? $_SERVER['PHP_SELF'] . '?' : $_SERVER['REQUEST_URI'] . '&';
if ($req->isRequest ('year')) $url_year = $req->getRequest ('year');
if ($db->getNumRows($date_result) > 0) {
$copy_investor_newsletter .= $tab0 . '<table class="table table-bordered table-responsive"><tbody><thead><tr><th>January</th><th>Feburay</th><th>March</th><th>April</th><th>May</th><th>June</th><th>July</th><th>August</th><th>September</th><th>October</th><th>November</th><th>December</th></tr></thead>' . $retn;
while ($data = $db->getNextRow($date_result)) {
if (substr ($data['date'], 0, 4) != $current_year) {
$current_year = substr ($data['date'], 0, 4);
if (!isset ($latest_year)) $latest_year = $current_year;
if (!isset ($url_year)) {
$navsel = ' class="ActNav"';
$url_year = $current_year;
} elseif ($url_year == $current_year) {
$navsel = ' class="ActNav"';
$selected_year = $url_year;
} else $navsel = '';
$copy_investor_newsletter .= $tab1 . '<tr>';
// if ($url_year == $current_year) {
/*
* read and display all newsletters for selected year
*/
$resource_where_conditions = '`publish` = \'y\' and `category_id` = ' . $cat_data['id'] . ' and substr(`date`,1,4) = \'' . $current_year . '\'';
$resource_result = $db->selectByStrings($resource_data_fields, '`resource`', $resource_where_conditions, '`date` desc');
if ($db->getNumRows($resource_result) > 0) {
// $copy_investor_newsletter .= $retn . $tab2 . '<ul>' . $retn;
while ($data = $db->getNextRow($resource_result)) {
$copy_investor_newsletter .= $tab3 . '<td>' . $data['heading'] . '</td>' . $retn;
}
// $copy_investor_newsletter .= $tab2 . '</ul>' . $retn . $tab1;
}
// }
$copy_investor_newsletter .= '</tr>' . $retn;
}
}
$copy_investor_newsletter .= $tab0 . '</tbody></table>' . $retn . $retn;
}
}
}

Try:
... ORDER BY YEAR(`date`) DESC, MONTH(`date`) ASC
See also the documentation of YEAR and MONTH

Related

How can I order a table by year descending and by month assending?

I'm trying to build a html table from a mysql database. The months of the year will be the across the top of the table(Jan-Dec), and the years will be the first column on the left, 2015 at the top and 2008 at the bottom. Currently I have it ordered by date, descending. This means the latest item will be at the top left position. However I need it to be sorted by ASC for the months of the year, and DSC for the years. I'm assuming I need to user DATE_FORMAT but I'm not sure how to implement this. The date format in the database is like this: 2014-07-01
$resource_where_conditions = '`publish` = \'y\' and `category_id` = ' . $cat_data['id'];
$date_result = $db->selectByStrings($resource_data_fields, '`resource`', $resource_where_conditions, '`date` desc');
$current_year = '';
$base_url_query = (_USE_SEO_URLS === true) ? $_SERVER['PHP_SELF'] . '?' : $_SERVER['REQUEST_URI'] . '&';
if ($req->isRequest ('year')) $url_year = $req->getRequest ('year');
if ($db->getNumRows($date_result) > 0) {
$copy_investor_newsletter .= $tab0 . '<table class="table table-bordered table-responsive"><tbody><thead><tr><th>January</th><th>Feburay</th><th>March</th><th>April</th><th>May</th><th>June</th><th>July</th><th>August</th><th>September</th><th>October</th><th>November</th><th>December</th></tr></thead>' . $retn;
while ($data = $db->getNextRow($date_result)) {
if (substr ($data['date'], 0, 4) != $current_year) {
$current_year = substr ($data['date'], 0, 4);
if (!isset ($latest_year)) $latest_year = $current_year;
if (!isset ($url_year)) {
$navsel = ' class="ActNav"';
$url_year = $current_year;
} elseif ($url_year == $current_year) {
$navsel = ' class="ActNav"';
$selected_year = $url_year;
} else $navsel = '';
$copy_investor_newsletter .= $tab1 . '<tr>';
// if ($url_year == $current_year) {
/*
* read and display all newsletters for selected year
*/
$resource_where_conditions = '`publish` = \'y\' and `category_id` = ' . $cat_data['id'] . ' and substr(`date`,1,4) = \'' . $current_year . '\'';
$resource_result = $db->selectByStrings($resource_data_fields, '`resource`', $resource_where_conditions, '`date` desc');
if ($db->getNumRows($resource_result) > 0) {
// $copy_investor_newsletter .= $retn . $tab2 . '<ul>' . $retn;
while ($data = $db->getNextRow($resource_result)) {
$copy_investor_newsletter .= $tab3 . '<td>' . $data['heading'] . '</td>' . $retn;
}
// $copy_investor_newsletter .= $tab2 . '</ul>' . $retn . $tab1;
}
// }
$copy_investor_newsletter .= '</tr>' . $retn;
}
}
$copy_investor_newsletter .= $tab0 . '</tbody></table>' . $retn . $retn;
}
Try this SQL query to get your desired ordering:
SELECT * FROM Table ORDER BY YEAR(date) DESC, MONTH(date) DESC
Don't fully understand, what is the difference between what you have now and what you want to get
But I think you should look in the direction of:
select date_format(date, '%c') month, date_format(date, '%Y') year, id, name, etc
from ... order by month ASC, year DESC
So you select month in numeric presentation and then you can order by it.

OSCommerce price schedule inconsistent behaviour

Working on a problem with an "old" shop in OSCommerce. It's a multistore configuration which is tweaked by the previous owner. I have 2 similar products with a price schedule or quantity price break feature.
The problem is 1 of the 2 products is not reacting consistent when added to cart or showing the product page.
1st product: has a price schedule of >5, >10, >20 and >30, with prices from high to low.
2nd product: has the same schedule but is somehow shown the other way around: >30, >20, >10 and >5 with prices from low to high.
The weird thing is that the option sort_order does not exist in the price schedule table so the way that the quantity order is shown is random, but always from high to low or low to high.
The first product shows the correct price in the shopping cart, the second product always shows the highest price at any quantity, where the shopping cart should adjust the price according to the price schedule data.
Done so far without any luck:
Checked the price schedule configuration in backend
Checked product configuration in backend and rechecked in Database
Checked all related database tables
After discovering that the only difference between the products are: product name, product image and product_id, gave the product an product_id close to the working one. Also changed all the related database entry's
Make a copy of the correctly working product and add a price schedule as well.
Here is the code of the class which generates the price_schedule:
<?php
/*
$Id: price_schedule.php,v 1.0 2004/08/23 22:50:52 rmh Exp $
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/
/*
price_schedule.php - module to support customer classes with quantity pricing
Originally Created 2003, Beezle Software based on some code mods by WasaLab Oy (Thanks!)
Modified by Ryan Hobbs (hobbzilla)
*/
class PriceFormatter {
var $hiPrice;
var $lowPrice;
var $quantity;
var $hasQuantityPrice;
var $hasSpecialPrice;
var $qtyPriceBreaks;
function PriceFormatter($prices=NULL) {
$this->productsID = -1;
$this->hasQuantityPrice=false;
$this->hasSpecialPrice=false;
$this->hiPrice=-1;
$this->lowPrice=-1;
$this->thePrice = -1;
$this->specialPrice = -1;
$this->qtyBlocks = 1;
$this->qtyPriceBreaks = 0;
if($prices) {
$this->parse($prices);
}
}
function encode() {
$str = $this->productsID . ":"
. (($this->hasQuantityPrice == true) ? "1" : "0") . ":"
. (($this->hasSpecialPrice == true) ? "1" : "0") . ":"
. $this->quantity[1] . ":"
. $this->quantity[2] . ":"
. $this->quantity[3] . ":"
. $this->quantity[4] . ":"
. $this->price[1] . ":"
. $this->price[2] . ":"
. $this->price[3] . ":"
. $this->price[4] . ":"
. $this->thePrice . ":"
. $this->specialPrice . ":"
. $this->qtyBlocks . ":"
. $this->taxClass;
return $str;
}
function decode($str) {
list($this->productsID,
$this->hasQuantityPrice,
$this->hasSpecialPrice,
$this->quantity[1],
$this->quantity[2],
$this->quantity[3],
$this->quantity[4],
$this->price[1],
$this->price[2],
$this->price[3],
$this->price[4],
$this->thePrice,
$this->specialPrice,
$this->qtyBlocks,
$this->taxClass) = explode(":", $str);
$this->hasQuantityPrice = (($this->hasQuantityPrice == 1) ? true : false);
$this->hasSpecialPrice = (($this->hasSpecialPrice == 1) ? true : false);
}
function parse($prices) {
global $customer_group_id, $customer_group_type, $customer_group_discount;
if (!tep_not_null($customer_group_id)) {
$customer_group_id = VISITOR_PRICING_GROUP;
$check_group_query = tep_db_query("select customers_groups_type, customers_groups_discount from " . TABLE_CUSTOMERS_GROUPS . " where customers_groups_id = '" . (int)$customer_group_id . "'");
$check_group = tep_db_fetch_array($check_group_query);
$customer_group_type = $check_group['customers_groups_type'];
$customer_group_discount = $check_group['customers_groups_discount'];
}
$this->productsID = $prices['products_id'];
$this->hasQuantityPrice=false;
$this->hasSpecialPrice=false;
// if ($customer_group_type != '1') {
// $price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and customers_groups_id = '" . (int)$customer_group_id . "' and stores_id = '" . STORES_ID . "'");
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'");
$this->qtyPriceBreaks = tep_db_num_rows($price_schedule_query);
$this->thePrice = $prices['products_price'];
$this->specialPrice = $prices['specials_new_products_price'];
// } else {
// $this->qtyPriceBreaks = 0;
// $this->thePrice = $prices['products_price'] * (100 - $customer_group_discount)/100;
// $this->specialPrice = $prices['specials_new_products_price'];
// if ($this->thePrice < $this->specialPrice) $this->specialPrice = "";
// }
$this->hiPrice = $this->thePrice;
$this->lowPrice = $this->thePrice;
$this->hasSpecialPrice = tep_not_null($this->specialPrice);
$this->qtyBlocks = $prices['products_qty_blocks'];
$this->taxClass=$prices['products_tax_class_id'];
$n = 0;
if ($this->qtyPriceBreaks > 0 ) {
while ($price_schedule = tep_db_fetch_array($price_schedule_query)) {
$this->price[$n]=$price_schedule['products_groups_price'];
$this->quantity[$n]=$price_schedule['products_groups_price_qty'];
if ($this->quantity[$n] == '1') {
$this->thePrice = $this->price[$n];
$this->hiPrice = $this->thePrice;
$this->lowPrice = $this->thePrice;
} else {
$this->hasQuantityPrice = true;
}
$n += 1;
}
}
for($i=0; $i<$this->qtyPriceBreaks; $i++) {
if ($this->hasSpecialPrice == true) {
$this->hiPrice = $this->specialPrice;
if ($this->price[$i] > $this->specialPrice) {
$this->price[$i] = $this->specialPrice;
}
}
if ($this->hasQuantityPrice == true) {
if ($this->price[$i] > $this->hiPrice) {
$this->hiPrice = $this->price[$i];
}
if ($this->price[$i] < $this->lowPrice) {
$this->lowPrice = $this->price[$i];
}
}
}
}
function loadProduct($product_id, $language_id=1)
{
$sql="select pd.products_name, p.products_model, p.products_image, p.products_leadtime, p.products_id, p.manufacturers_id, p.products_price, p.products_weight, p.products_unit, p.products_qty_blocks, p.products_tax_class_id, p.distributors_id, IF(s.status = '1' AND s.stores_id = '" . STORES_ID . "', s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status = '1' AND s.stores_id = '" . STORES_ID . "', s.specials_new_products_price, p.products_price) as final_price from " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, ((" . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m on p.manufacturers_id = m.manufacturers_id, " . TABLE_PRODUCTS_DESCRIPTION . " pd) left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id and s.stores_id = '" . STORES_ID . "') INNER JOIN " . TABLE_PRODUCTS_TO_STORES . " p2s ON p.products_id = p2s.products_id where p2s.stores_id = '" . STORES_ID . "' AND p.products_status = '1' and p.products_id = '" . (int)$product_id . "' and pd.products_id = '" . (int)$product_id . "' and pd.language_id = '". (int)$language_id ."'";
$product_info_query = tep_db_query($sql);
$product_info = tep_db_fetch_array($product_info_query);
$this->parse($product_info);
return $product_info;
}
function computePrice($qty) {
$qty = $this->adjustQty($qty);
$price = $this->thePrice;
if ($this->hasSpecialPrice == true) {
$price = $this->specialPrice;
}
if ($this->hasQuantityPrice == true) {
for ($i=0; $i<$this->qtyPriceBreaks; $i++) {
if (($this->quantity[$i] > 0) && ($qty >= $this->quantity[$i])) {
$price = $this->price[$i];
}
}
}
return $price;
}
// Force QTY_BLOCKS granularity
function adjustQty($qty) {
$qb = $this->getQtyBlocks();
if ($qty < 1) {
$qty = 0;
return $qty;
}
if ($qb >= 1) {
if ($qty < $qb) {
$qty = $qb;
}
if (($qty % $qb) != 0) {
$qty += ($qb - ($qty % $qb));
}
}
return $qty;
}
function getQtyBlocks() {
return $this->qtyBlocks;
}
function getPrice() {
return $this->thePrice;
}
function getLowPrice() {
return $this->lowPrice;
}
function getHiPrice() {
return $this->hiPrice;
}
function hasSpecialPrice() {
return $this->hasSpecialPrice;
}
function hasQuantityPrice() {
return $this->hasQuantityPrice;
}
function getPriceString($style='productPriceInBox') {
global $currencies, $customer_id;
// If you want to change the format of the price/quantity table
// displayed on the product information page, here is where you do it.
if (($this->hasSpecialPrice == true) && ($this->hasQuantityPrice == false)) {
$lc_text = ' <s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span>';
}
if($this->hasQuantityPrice == true) {
$lc_text = '<table align="top" border="0" cellspacing="0" cellpadding="0"><tr><td align="center" colspan="2"><b>' . ($this->hasSpecialPrice == true ? '<s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span> ' : 'vanaf ' . $currencies->display_price($this->lowPrice, tep_get_tax_rate($this->taxClass)) ) . '</b></td></tr>';
for($i=0; $i<=$this->qtyPriceBreaks; $i++) {
if(($this->quantity[$i] > 0) && ($this->price[$i] > $this->specialPrice)) {
$lc_text .= '<tr><td class='.$style.' align="right">> ' . $this->quantity[$i] . ' </td><td class='.$style.'>' . $currencies->display_price($this->price[$i], tep_get_tax_rate($this->taxClass)) . '</td></tr>';
}
}
$lc_text .= '</table>';
} else {
if ($this->hasSpecialPrice == true) {
$lc_text = ' <s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span>';
} else {
$lc_text = ' ' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '';
}
}
// if (VISITOR_PRICING_GROUP < '0' && !tep_session_is_registered('customer_id')) {
// return '';
// } else {
return $lc_text;
// }
}
function getPriceStringShort() {
global $currencies, $customer_id;
if (($this->hasSpecialPrice == true) && ($this->hasQuantityPrice == false)) {
$lc_text = '<div class="priceold">' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</div><div class="pricenew">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</div>';
} elseif ($this->hasQuantityPrice == true) {
$lc_text = '<div class="vanaf">vanaf</div><div class="price">' . $currencies->display_price($this->lowPrice, tep_get_tax_rate($this->taxClass)) . ' </div>';
} else {
$lc_text = '<div class="price">' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</div>';
}
// if (VISITOR_PRICING_GROUP < '0' && !tep_session_is_registered('customer_id')) {
// return TEXT_LOGIN_TO_SEE_PRICES;
// } else {
return $lc_text;
// }
}
}
?>
I'm not experienced enough to decipher the class and find strange things, if you need more info, do not hesitate to ask.
Any help would be apreciated.
As I understand your question, you would like the product prices to be ordered consistently. I'm aware of the addons you mention but I'm not very familiar with them. That being said you can try to change this line...
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'");
to
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'" . " ORDER BY products_groups_price ASC");
As I said, I'm not familiar with exactly how the addons you mentioned work but I'd start by adding ordering to the mysql query. This approach has worked for me on numerous occasions with various addons.

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

Wrong calendar displaying after server crash

Few days ago server crashed and was down for few hours, after server become available, my calendar started to display wrong data. It had to show me current month and 5 next(half a year in total). Server data is correct. Any ideas whats wrong with calendar? Does mysql server time can make my calendar show wrong data?
if (!isset($_MONTH))
$_MONTH = 6;
if (isset($_POST['subscribe_month']))
$_MONTH = $class->_dig($_POST['subscribe_month']);
$sql = mysql_query("SELECT d.header, d.id FROM " . $class->_cfg['pfx'] . "workshops as w
LEFT JOIN " . $class->_cfg['pfx'] . "workshops_date as wd ON wd.cid=w.id
LEFT JOIN " . $class->_cfg['pfx'] . "dictionary as d ON d.id=wd.city
WHERE w.public='1' and wd.public='1' and wd.date_end>='" . date("Y-m-d") . "' a
nd wd.predprosomtr='0' " . $where . " ORDER BY d.rang");
$CityList = array();
while ($_sql = mysql_fetch_assoc($sql)) {
$CityList[$_sql['id']] = $_sql['header'];
}
if ($Fcity && $Fcity != 0)
$where.=" and d.id=" . $Fcity . "";
elseif ($_POST['city'] && $class->_dig($_POST['city']) > 0)
$where.=" and d.id=" . $class->_dig($_POST['city']) . "";
if ($CitySearch != 0)
$where.=" and wd.city=" . $CitySearch . " ";
$sql = mysql_query("SELECT w.header, w.direction, w.subheader, wd.colsmonth, wd.is_new, wd.public_date_finish, wd.p_date_finish, w.aliaslink, wd.aliaslink as wd_aliaslink, w.direction, wd.city, wd.date_start, d.header as city_name, wd.date_end, wd.cid, wd.id as wd_id, w.id as w_id FROM " . $class->_cfg['pfx'] . "workshops as w
LEFT JOIN " . $class->_cfg['pfx'] . "workshops_date as wd ON wd.cid=w.id
LEFT JOIN " . $class->_cfg['pfx'] . "dictionary as d ON d.id=wd.city
WHERE w.public='1' and wd.public='1' and wd.date_end>='" . date("Y-m-d") . "' and w.direction<>'' and wd.predprosomtr='0' " . $where . " ORDER BY wd.date_start, wd.city");
//$output.=$where;
$month = 12;
$year = date("Y");
while ($_sql = mysql_fetch_assoc($sql)) {
$view = true;
if ($_sql['public_date_finish'] == '1' && $_sql['p_date_finish'] < date("Y-m-d"))
$view = false;
if ($view) {
$arWorkshops[$_sql['w_id']] = $_sql;
if (!isset($arWorkshopsCity[$_sql['cid']][$_sql['city']]) && $_sql['city'] > 0)
$arWorkshopsCity[$_sql['cid']][$_sql['city']] = $_sql['city'];
if (isset($arWorkshopsDate[$_sql['cid']]['count']))
$arWorkshopsDate[$_sql['cid']]['count'] = $arWorkshopsDate[$_sql['cid']]['count'] + 1;
else
$arWorkshopsDate[$_sql['cid']]['count'] = 1;
$direct = explode('#', $_sql['direction']);
for ($i = 0; $i < count($direct); $i++) {
if (trim($direct[$i]) != '') {
$arDirectionList[$direct[$i]] = $direct[$i];
}
}
//$arDirectionList[$_sql['direction']]=$_sql['direction'];
if (!isset($arWorkshopsDate[$_sql['cid']][ceil($class->convert_date($_sql['date_start'], '.', "month"))]))
$arWorkshopsDate[$_sql['cid']][ceil($class->convert_date($_sql['date_start'], '.', "month"))] = $_sql;
if ($class->convert_date($_sql['date_start'], '.', "month") < $month && $class->convert_date($_sql['date_start'], '.', "year") == $year) {
$month = $class->convert_date($_sql['date_start'], '.', "month");
$year = $class->convert_date($_sql['date_start'], '.', "year");
}
//if($class->convert_date($_sql['date_start'], '.', "year")==(date("Y")+1))$year=$class->convert_date($_sql['date_start'], '.', "year");
//$output.=$_sql['header']."-".$_sql['date_start']."-".$_sql['wd_id']."<br>";
}
}
//var_dump($arWorkshopsDate[185]);
$output.='<table class="table"><tr><th width="60"> </th><th class="first" style="width:auto">Название</th>';
if ($_MONTH == 12)
$w = "5%"; else
$w = "9%";
for ($i = $month; $i < ($month + $_MONTH); $i++) {
if ($year == date("Y"))
$m = $i;else
$m++;
if ($m <= 12 && $year == date("Y")) {
$output.='<th class="month" style="width:' . $w . '">' . $class->convert_date($m, '.', "myear") . ' <span>' . $year . '</span></th>';
} else {
if ($m > 12) {
$m = 1;
$year = $year + 1;
}
$output.='<th class="month" style="width:' . $w . '">' . $class->convert_date($m, '.', "myear") . ' <span>' . $year . '</span></th>';
}
}
$output.=' <th style="width:10%">';
if ($typeblock == 'webinars')
$output.='Формат';
else
$output.='Город';
$output.='</th></tr>';
if (isset($arWorkshops)) {
//foreach($arWorkshops as $LO=>$listOrd){
foreach ($arWorkshops as $k => $value) {
if (!$direction || $direction == 0)
$direction2 = $class->_direction($value['direction']);
else
$direction2 = $direction;
foreach ($arWorkshopsCity[$k] as $LO => $listOrd) {
$output2 = "";
$link_date = "";
$pt = 0;
$m_nth = ceil($month);
$is_new_class = '';
for ($i = ceil($month); $i < ($month + $_MONTH); $i++) {
if ($m_nth > 12)
$m_nth = 1;
if (isset($arWorkshopsDate[$k][$m_nth]) && $arWorkshopsDate[$k][$m_nth]['city'] == $LO) {
$pt++;
if ($pt == 1)
$city_name = $arWorkshopsDate[$k][$m_nth]['city_name'];
//if(isset($_TYPE) && $_TYPE!=0)$output.='<td class="date"><a href="/'.$typeblock.'/'.$value['aliaslink'].'/'.$arWorkshopsDate[$k][$i]['wd_aliaslink'].'/">';
//else
if (($arWorkshopsDate[$k][$m_nth]['is_new'] == '1') || ($arWorkshopsDate[$k][$m_nth + 1]['is_new'] == '1')) {
$is_new_class = " it_is_new";
} else {
$is_new_class = '';
}
$output2.='<td class="date"><a href="/' . $typeblock . '/' . $arDictionaryID[$direction2]['aliaslink'] . '/' . $value['aliaslink'] . '/' . $arWorkshopsDate[$k][$m_nth]['wd_aliaslink'] . '/">';
$link_date = '/' . $typeblock . '/' . $arDictionaryID[$direction2]['aliaslink'] . '/' . $value['aliaslink'] . '/' . $arWorkshopsDate[$k][$m_nth]['wd_aliaslink'] . '/';
if ($arWorkshopsDate[$k][$m_nth]['colsmonth'] > 0)
$output2.=$class->convert_date($arWorkshopsDate[$k][$m_nth]['date_start'], '.', "day_month") . "</a><br />" . $arWorkshopsDate[$k][$m_nth]['colsmonth'] . " мес.";
elseif ($arWorkshopsDate[$k][$m_nth]['date_start'] == $arWorkshopsDate[$k][$m_nth]['date_end'])
$output2.=$class->convert_date($arWorkshopsDate[$k][$m_nth]['date_start'], '.', "day_month") . "</a>";
else
$output2.=$class->convert_date($arWorkshopsDate[$k][$m_nth]['date_start'], '.', "day_month") . "<br />-" . $class->convert_date($arWorkshopsDate[$k][$m_nth]['date_end'], '.', "day_month") . "</a>";
$output2.='</td>';
}else {
$output2.='<td></td>';
}
$m_nth++;
}
if (($arWorkshopsDate[$k][$m_nth]['is_new'] == '1')) {
$is_new_class = " it_is_new";
}
$output.='<tr><td class="' . $is_new_class . '"> </td><td>';
//if(isset($_TYPE) && $_TYPE!=0)$output.='<strong>'.$value['header'].'</strong>';
//else
if ($pt == 1 && $arWorkshopsDate[$k]['count'] == 1)
$link = $link_date;
else
$link = '/' . $typeblock . '/' . $arDictionaryID[$direction2]['aliaslink'] . '/' . $value['aliaslink'] . '/';
$output.='<a href="' . $link . '"><strong>' . $value['header'] . '</strong>';
if (trim($value['subheader']) != '')
$output.=': ' . $value['subheader'] . '';
$output.='</a>';
$output.='</td>';
$output.=$output2;
$output.=' <td class="city">' . $city_name . '</td></tr>';
}
}
//}
}
$output.='</table>';
?>
Issue solved. By default some "good" coder made it show only from 12th month in $month = 12;
I just changed it to $month = date("m"); And this solved my issue

Change 'sort by' in plugin

I'm looking to edit the Gigpress code so that when events are not 'grouped by artist', they are still ordered by event date rather than artist name.
The Gigpress sidebar does this no problem so I figure that the main plugin should be able to be configured to do this somehow. Just can't get my head around this.
The plugin code is
<?php
// These two functions are for backwards-compatibility the shortcodes used in GigPress < 2.0
function gigpress_upcoming($filter = null, $content = null) {
if(!is_array($filter)) $filter = array();
$filter['scope'] = 'upcoming';
return gigpress_shows($filter, $content);
}
function gigpress_archive($filter = null, $content = null) {
if(!is_array($filter)) $filter = array();
$filter['scope'] = 'past';
return gigpress_shows($filter, $content);
}
function gigpress_shows($filter = null, $content = null) {
global $wpdb, $gpo;
$further_where = $limit = '';
extract(shortcode_atts(array(
'tour' => FALSE,
'artist' => FALSE,
'venue' => FALSE,
'limit' => FALSE,
'scope' => 'upcoming',
'sort' => FALSE,
'group_artists' => 'yes',
'artist_order' => 'custom',
'show_menu' => FALSE,
'show_menu_count' => FALSE,
'menu_sort' => FALSE,
'menu_title' => FALSE,
'year' => FALSE,
'month' => FALSE
), $filter)
);
$total_artists = $wpdb->get_var("SELECT count(*) from " . GIGPRESS_ARTISTS);
// Date conditionals and sorting based on scope
switch($scope) {
case 'upcoming':
$date_condition = "show_expire >= '" . GIGPRESS_NOW . "'";
if(empty($sort)) $sort = 'asc';
break;
case 'past':
$date_condition = "show_expire < '" . GIGPRESS_NOW . "'";
if(empty($sort)) $sort = 'desc';
break;
case 'today':
$date_condition = "show_expire >= '".GIGPRESS_NOW."' AND show_date <= '".GIGPRESS_NOW."'";
if(empty($sort)) $sort = 'asc';
break;
case 'all':
$date_condition = "show_expire != ''";
if(empty($sort)) $sort = 'desc';
break;
}
// Artist, tour and venue filtering
if($artist) $further_where .= ' AND show_artist_id = ' . $wpdb->prepare('%d', $artist);
if($tour) $further_where .= ' AND show_tour_id = ' . $wpdb->prepare('%d', $tour);
if($venue) $further_where .= ' AND show_venue_id = ' . $wpdb->prepare('%d', $venue);
// Date filtering
// Query vars take precedence over function vars
if(isset($_REQUEST['gpy'])) {
$year = $_REQUEST['gpy'];
if(isset($_REQUEST['gpm'])) {
$month = $_REQUEST['gpm'];
} else {
unset($month);
}
$no_limit = TRUE;
}
// Validate year and date parameters
if($year || $month) {
if($year) {
if(is_numeric($year) && strlen($year) == 4) {
$year = round($year);
} else {
$year = date('Y', current_time('timestamp'));
}
} else {
// We've only specified a month, so we'll assume the year is current
$year = date('Y', current_time('timestamp'));
}
if($month) {
if($month == 'current') {
$month = date('m', current_time('timestamp'));
} elseif(round($month) == 0) {
// Probably using a month name
$month = date('m', strtotime($month));
} elseif(round($month) < 10) {
// Make sure the month is padded through 09
$month = str_pad($month, 2, 0, STR_PAD_LEFT);
} elseif(round($month) < 13) {
// Between 10 and 12 we're OK
$month = $month;
} else {
// Bogus month value (not a string and > 12)
// Sorry, bailing out. Your "month" will be ignored. Dink.
$month = FALSE;
}
$start_month = $end_month = $month;
}
if(!$month) {
$start_month = '01';
$end_month = '12';
}
$start = $year.'-'.$start_month.'-01';
$end = $year.'-'.$end_month.'-31';
$further_where .= ' AND show_date BETWEEN '.$wpdb->prepare('%s', $start).' AND '.$wpdb->prepare('%s', $end);
}
$limit = ($limit && !$no_limit) ? ' LIMIT ' . $wpdb->prepare('%d', $limit) : '';
$artist_order = ($artist_order == 'custom') ? "artist_order ASC," : '';
// With the new 'all' scope, we should probably have a third message option, but I'm too lazy
// Really, there should just be one generic 'no shows' message. Oh well.
$no_results_message = ($scope == 'upcoming') ? wptexturize($gpo['noupcoming']) : wptexturize($gpo['nopast']);
ob_start();
// Are we showing our menu?
if($show_menu) {
$menu_options = array();
$menu_options['scope'] = $scope;
$menu_options['type'] = $show_menu;
if($menu_title) $menu_options['title'] = $menu_title;
if($show_menu_count) $menu_options['show_count'] = $show_menu_count;
if($menu_sort) $menu_options['sort'] = $menu_sort;
if($artist) $menu_options['artist'] = $artist;
if($tour) $menu_options['tour'] = $tour;
if($venue) $menu_options['venue'] = $venue;
include gigpress_template('before-menu');
echo gigpress_menu($menu_options);
include gigpress_template('after-menu');
}
// If we're grouping by artist, we'll unfortunately have to first get all artists
// Then make a query for each one. Looking for a better way to do this.
if($group_artists == 'yes' && !$artist && $total_artists > 1) {
$artists = $wpdb->get_results("SELECT * FROM " . GIGPRESS_ARTISTS . " ORDER BY " . $artist_order . "artist_name ASC");
foreach($artists as $artist_group) {
$shows = $wpdb->get_results("SELECT * FROM " . GIGPRESS_ARTISTS . " AS a, " . GIGPRESS_VENUES . " as v, " . GIGPRESS_SHOWS ." AS s LEFT JOIN " . GIGPRESS_TOURS . " AS t ON s.show_tour_id = t.tour_id WHERE " . $date_condition . " AND show_status != 'deleted' AND s.show_artist_id = " . $artist_group->artist_id . " AND s.show_artist_id = a.artist_id AND s.show_venue_id = v.venue_id " . $further_where . " ORDER BY s.show_date " . $sort . ",s.show_expire " . $sort . ",s.show_time ". $sort . $limit);
if($shows) {
// For each artist group
$some_results = TRUE;
$current_tour = '';
$i = 0;
$showdata = array(
'artist' => wptexturize($artist_group->artist_name),
'artist_id' => $artist_group->artist_id
);
include gigpress_template('shows-artist-heading');
include gigpress_template('shows-list-start');
foreach($shows as $show) {
// For each individual show
$showdata = gigpress_prepare($show, 'public');
if($showdata['tour'] && $showdata['tour'] != $current_tour && !$tour) {
$current_tour = $showdata['tour'];
include gigpress_template('shows-tour-heading');
}
$class = $showdata['status'];
++ $i; $class .= ($i % 2) ? '' : ' gigpress-alt';
if(!$showdata['tour'] && $current_tour) {
$current_tour = '';
$class .= ' divider';
}
$class .= ($showdata['tour'] && !$tour) ? ' gigpress-tour' : '';
include gigpress_template('shows-list');
}
include gigpress_template('shows-list-end');
}
}
if($some_results) {
// After all artist groups
include gigpress_template('shows-list-footer');
} else {
// No shows from any artist
include gigpress_template('shows-list-empty');
}
} else {
// Not grouping by artists
$shows = $wpdb->get_results("
SELECT * FROM " . GIGPRESS_ARTISTS . " AS a, " . GIGPRESS_VENUES . " as v, " . GIGPRESS_SHOWS ." AS s LEFT JOIN " . GIGPRESS_TOURS . " AS t ON s.show_tour_id = t.tour_id WHERE " . $date_condition . " AND show_status != 'deleted' AND s.show_artist_id = a.artist_id AND s.show_venue_id = v.venue_id " . $further_where . " ORDER BY s.show_date " . $sort . ",s.show_expire " . $sort . ",s.show_time " . $sort . $limit);
if($shows) {
$current_tour = '';
$i = 0;
include gigpress_template('shows-list-start');
foreach($shows as $show) {
// For each individual show
$showdata = gigpress_prepare($show, 'public');
if($showdata['tour'] && $showdata['tour'] != $current_tour && !$tour) {
$current_tour = $showdata['tour'];
include gigpress_template('shows-tour-heading');
}
$class = $showdata['status'];
++ $i; $class .= ($i % 2) ? '' : ' gigpress-alt';
if(!$showdata['tour'] && $current_tour) {
$current_tour = '';
$class .= ' divider';
}
$class .= ($showdata['tour'] && !$tour) ? ' gigpress-tour' : '';
include gigpress_template('shows-list');
}
include gigpress_template('shows-list-end');
include gigpress_template('shows-list-footer');
} else {
// No shows to display
include gigpress_template('shows-list-empty');
}
}
echo('<!-- Generated by GigPress ' . GIGPRESS_VERSION . ' -->
');
return ob_get_clean();
}
function gigpress_menu($options = null) {
global $wpdb, $wp_locale, $gpo;
extract(shortcode_atts(array(
'type' => 'monthly',
'base' => get_permalink(),
'scope' => 'upcoming',
'title' => FALSE,
'id' => 'gigpress_menu',
'show_count' => FALSE,
'artist' => FALSE,
'tour' => FALSE,
'venue' => FALSE,
'sort' => 'desc'
), $options));
$base .= (strpos($base, '?') === FALSE) ? '?' : '&';
// Date conditionals based on scope
switch($scope) {
case 'upcoming':
$date_condition = ">= '" . GIGPRESS_NOW . "'";
break;
case 'past':
$date_condition = "< '" . GIGPRESS_NOW . "'";
break;
case 'all':
$date_condition = "!= ''";
}
$further_where = '';
// Artist, tour and venue filtering
if($artist) $further_where .= ' AND show_artist_id = ' . $wpdb->prepare('%d', $artist);
if($tour) $further_where .= ' AND show_tour_id = ' . $wpdb->prepare('%d', $tour);
if($venue) $further_where .= ' AND show_venue_id = ' . $wpdb->prepare('%d', $venue);
// Variable operajigamarations based on monthly vs. yearly
switch($type) {
case 'monthly':
$sql_select_extra = 'MONTH(show_date) AS month, ';
$sql_group_extra = ', MONTH(show_date)';
$title = ($title) ? wptexturize(strip_tags($title)) : __('Select Month');
$current = (isset($_REQUEST['gpy']) && isset($_REQUEST['gpm'])) ? $_REQUEST['gpy'].$_REQUEST['gpm'] : '';
break;
case 'yearly':
$sql_select_extra = $sql_group_extra = '';
$title = ($title) ? wptexturize(strip_tags($title)) : __('Select Year');
$current = (isset($_REQUEST['gpy'])) ? $_REQUEST['gpy'] : '';
}
// Build query
$dates = $wpdb->get_results("
SELECT YEAR(show_date) AS year, " . $sql_select_extra . " count(show_id) as shows
FROM ".GIGPRESS_SHOWS."
WHERE show_status != 'deleted'
AND show_date " . $date_condition . $further_where . "
GROUP BY YEAR(show_date)" . $sql_group_extra . "
ORDER BY show_date " . $sort);
ob_start();
if($dates) : ?>
<select name="gigpress_menu" class="gigpress_menu" id="<?php echo $id; ?>">
<option value="<?php echo $base; ?>"><?php echo $title; ?></option>
<?php foreach($dates as $date) : ?>
<?php $this_date = ($type == 'monthly') ? $date->year.$date->month : $date->year; ?>
<option value="<?php echo $base.'gpy='.$date->year; if($type == 'monthly') echo '&gpm='.$date->month; ?>"<?php if($this_date == $current) : ?> selected="selected"<?php endif; ?>>
<?php if($type == 'monthly') echo $wp_locale->get_month($date->month).' '; echo $date->year; ?>
<?php if($show_count && $show_count == 'yes') : ?>(<?php echo $date->shows; ?>)<?php endif; ?>
</option>
<?php endforeach; ?>
</select>
<?php endif;
return ob_get_clean();
}
The line under // Not grouping by artists
Change from:
$shows = $wpdb->get_results("SELECT * FROM " . GIGPRESS_ARTISTS . " AS a, " . GIGPRESS_VENUES . " as v, " . GIGPRESS_SHOWS ." AS s LEFT JOIN " . GIGPRESS_TOURS . " AS t ON s.show_tour_id = t.tour_id WHERE " . $date_condition . " AND show_status != 'deleted' AND s.show_artist_id = a.artist_id AND s.show_venue_id = v.venue_id " . $further_where . " ORDER BY s.show_date " . $sort . ",s.show_expire " . $sort . ",s.show_time " . $sort . $limit);
To:
$shows = $wpdb->get_results("SELECT * FROM " . GIGPRESS_ARTISTS . " AS a, " . GIGPRESS_VENUES . " as v, " . GIGPRESS_SHOWS ." AS s LEFT JOIN " . GIGPRESS_TOURS . " AS t ON s.show_tour_id = t.tour_id WHERE " . $date_condition . " AND show_status != 'deleted' AND s.show_artist_id = a.artist_id AND s.show_venue_id = v.venue_id " . $further_where . " ORDER BY a.artist_name ASC,s.show_date " . $sort . ",s.show_expire " . $sort . ",s.show_time " . $sort . $limit);

Categories