I began to write a generic class for SELECT queries that looks like this:
class DbQuery
{
private $database;
public function __construct()
{
$db_config = array(
"type" => "mysql",
"host" => "localhost",
"port" => "3306",
"charset" => "utf8",
"db" => "dbname",
"user" => "user",
"password" => "topsecret"
);
$this->database = DatabaseFactory::getFactory()->getConnection($db_config);
}
public function Select($keys = array("*"), $table, $whereClauseArray = null, $orderValues = null, $orderDirection = null, $limitIndex = null, $limitLength = null)
{
$statement = "SELECT " . implode(',', $keys) . " FROM " . $table;
if (!empty($whereClauseArray)) {
$whereClauseString = " WHERE ";
$i = 0;
foreach ($whereClauseArray as $whereClause) {
if ($i > 0) {
$whereClauseString .= " " . $whereClause['link'] . " ";
}
$whereClauseString .= $whereClause['key'] . " " . $whereClause['operand'] . " :" . $whereClause['key'] . "_" . $i;
$i++;
}
$statement .= $whereClauseString;
}
if (!empty($orderValues)) {
$orderClause = " ORDER BY ";
foreach ($orderValues as $order) {
$orderClause .= $order . ", ";
}
$orderClause = substr($orderClause, 0, -2);
$statement .= $orderClause . " " . $orderDirection;
}
if ($limitIndex != null && $limitLength != null) {
$statement .= " LIMIT " . $limitIndex . "," . $limitLength;
}
$query = $this->database->prepare($statement . ";");
$file = $_SERVER["DOCUMENT_ROOT"] . '/../db.log';
$current = file_get_contents($file);
$current .= date("Y-m-d H:i:s", time()) . " => ";
$current .= "Statement: " . $statement . "\n";
file_put_contents($file, $current);
$j = 0;
foreach ($whereClauseArray as $whereClause) {
$keystring = ":" . $whereClause['key'] . "_" . $j;
$bindValue = trim(strip_tags($whereClause['value']));
$query->bindValue($keystring, $bindValue);
$file = $_SERVER["DOCUMENT_ROOT"] . '/../db.log';
$current = file_get_contents($file);
$current .= date("Y-m-d H:i:s", time()) . " => ";
$current .= "BindValue: " . $keystring . " -> " . trim(strip_tags($whereClause['value'])) . "\n";
file_put_contents($file, $current);
$j++;
}
// $query->execute();
if ($keys === "count(*)") {
return $query->fetchColumn(0);
} else {
return $query->fetchAll();
}
}
}
I call the function like that:
$obj_artikel_startseite = new DbQuery();
$obj_artikel_startseite->Select(array("*"), "psartikel", array(array("link" => "AND", "key" => "status", "value" => "freigeschaltet", "operand" => "="), array("link" => "OR", "key" => "status", "value" => "reserviert", "operand" => "=")), array("id"), "DESC", 0, 3)) {
As long as I leave the execution commented, I get a proper output in my db.log file:
2022-10-23 19:35:51 => Statement: SELECT * FROM psartikel WHERE status = :status_0 OR status = :status_1 ORDER BY id DESC
2022-10-23 19:35:51 => BindValue: :status_0 -> freigeschaltet
2022-10-23 19:35:51 => BindValue: :status_1 -> reserviert
But when I try to execute the prepared statement with binded values, it leads to an endless loop. I donĀ“t understand why.
Regards
Edit: Endless loop means the execution limit exceeds and the output in my log is about thousands, indentical entries...
Related
hi i have the following while loop :
while ($row = mysqli_fetch_array($result2)){
$elem_filho = $row['itempt_dim'];
$marcas = "{name: " . "'" . $elem_filho . "'" . ", color: " . "'" . $cor_alea . "'" . ", size: 1";
if (mysqli_num_rows($result2)) {
$dif = "},";
}
else {
$dif = "}]";
}
$vlk = $marcas . $dif;
print_r($vlk);
}
the thing is i had similar code and it worked this way, but the output is alway }, and i want the last item of the query to end with }]
i can't see what i am doing wrong
thanks in advance
With json_encode you code is simplified to:
$vlk = [];
while ($row = mysqli_fetch_array($result2)) {
$vlk[] = [
'name' => $row['itempt_dim'],
'color' => $cor_alea,
'size' => 1,
];
}
print_r(json_encode($vlk));
I am trying to build a search query based on the input from users, but I am having problems with the AND and WHERE keywords. Here is the code:
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array();
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
$where[] = $key . ' = ' . $value;
}
}
}
The output looks like this:
Array
(
[0] => gender = masculine
[1] => level = low
[2] => status = future
)
If no option is selected, it defaults to 'all' and it is excluded from the $where[].
I need to achieve this, or anything similar:
Array
(
[0] => WHERE gender = masculine
[1] => AND level = low
[2] => AND status = future
)
The WHERE must be appended only if one or more options have been selected and the AND must be appended only if two or more options have been selected.
In the code I am using I have 9 search inputs. To keep it clear I only displayed three in the snippet. Can you please help me figure this out?
Try this:I think you need the whereClause in string not in array,here you can choose any one from two and remove the other one.
<?php
$where=array();$flag=0;// use flag to identify the where/and
$whereClause="";
$criteria = array('gender' => "masculine", 'level' => "low", 'status' => "future");
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($flag == 0){
$where[] = " WHERE " .$key . ' = ' . $value;//if you need array
$whereClause='WHERE '.$key . ' = "' . $value.'"';//if you need string
}else{
$where[] = " AND " .$key . ' = ' . $value;
$whereClause .=' AND '.$key . ' = "' . $value.'"';
}
$flag++;
}
}
echo "<pre>";
print_r($where);
echo "</pre>";
echo $whereClause;
?>
You can do this :
$query = 'SELECT * FROM candidate ';
$where='';
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($where=='')
$where='WHERE '.$key . ' = ' . $value;
else
$where.=' AND '.$key . ' = ' . $value;
}
}
$query.=$where; //final query
You can use simple switch statement too
<?
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array();
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value)
{
if ($value !== 'all')
{
switch ($key)
{
case 1:
{
$query = " WHERE " .$key . ' = ' . $value;
break;
}
case 2:
{
$query = " AND " .$key . ' = ' . $value;
break;
}
case 3:
{
$query = " AND " .$key . ' = ' . $value;
break;
}
}
$where[] = $query;
}
}
}
You need to put one incrementer ($inc) and then put the conditions as:
$inc=1;
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($inc==1){
$where[] = 'Where '.$key . ' = ' . $value.'';
}else{
$where[] = 'AND '.$key . ' = ' . $value.'';
}
$inc++;
}
}
In My view there is one more clean way of achiving this:
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array("Where 1=1");
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
$where[] = 'AND '.$key . ' = ' . $value.' ';
}
}
}
I am trying to write some PHP that fits in to a larger method so that I can dynamically create a MySQL query.
I haven't included the code to the larger method that contains this code because I think the logic of this bit is self-contained.
So, I have a multi-dimensional array:
$where=array(array('username', 'pid', 'name'), array('=','<=', '='), array('alex',2,'james'));
which when I print_r() shows this structure:
Array
(
[0] => Array
(
[0] => username
[1] => pid
[2] => name
)
[1] => Array
(
[0] => =
[1] => <=
[2] => =
)
[2] => Array
(
[0] => alex
[1] => 2
[2] => james
)
)
What I would like to do if use the first value in each second level array to build up the start of the query such as
SELECT * FROM table WHERE username = alex
and then use the other values to build up the query such as (depending upon the number of items in the arrays)
SELECT * FROM table WHERE username = alex AND pid <= 2 AND name = james
Below is the code I have written
if (is_array($where[0])){
$i=0;
$field = $where[0][$i];
$operator = $where[1][$i];
$value= $where[2][$i];
$sql= "SELECT * FROM table WHERE {$field} {$operator} {$value}";
while($i=0 ) {
print $sql;
$i++;
}
while($i>0 AND $i< sizeof($where[0]))
$field = $where[0][$i];
$operator = $where[1][$i];
$value= $where[2][$i];
print $sql .= " AND {$field} {$operator} {$value}";
$i++;
}
However this prints out just one query
SELECT * FROM table WHERE username = alex AND username = alex
I am using PDO so in reality {$value} is replaced by ? and bound elsewhere in the method. I've just shown it here in full.
$sql = 'SELECT * FROM table WHERE';
for($i = 0; $i < count($where[0]); $i++){
$sql .= " {$where[0][$i]} {$where[1][$i]} {$where[2][$i]} AND";
}
$sql = substr($sql, 0, strlen($sql) - 4);
I personally would however save your statements like this:
$array = array('username = alex', 'pid <= 2');
If you needed the different parts of the statements, you could just do
explode(' ', $array[num]);
$companyFilter = "";
$auth = getFormulaAuth();
$companyFilter = "AND company_id = {$auth['company_id']} ";
$arguments = func_get_args();
if ($WhereFilterName_xxx) {
} else {
$db = new Database();
$this_get_table_form = getFormulaFormDetails($FormName);
$tbfields_data = Formula::getTBFields($this_get_table_form["id"], $db);
$q_string = "SELECT * FROM `" . $this_get_table_form["form_table_name"] . "`";
$valid_param_check = count($arguments) - 2;
$cache_key = "*";
if ($valid_param_check >= 1 && $valid_param_check % 3 == 0) {
$found_indexes = array();
$q_string_where = " WHERE ";
$search = " (NOT EXISTS(SELECT * FROM tbtrash_bin WHERE record_id = " . $this_get_table_form["form_table_name"] . ".id
AND form_id = " . $this_get_table_form["id"] . "
AND table_name='" . $this_get_table_form["form_table_name"] . "')) AND ";
$q_string_where .= $search;
for ($i = 2; $i < count($arguments); $i+=3) {
$field_key = $arguments[$i];
$operator = $arguments[$i + 1];
$value = $arguments[$i + 2];
if ($i > 2) {
$q_string_where .= " AND ";
}
$q_string_where .= " `" . $field_key . "` " . $operator;
if (($tbfields_data["" . $field_key]["field_input_type"] == "Number" || $tbfields_data["" . $field_key]["field_input_type"] == "Currency") || strtoupper($operator) == "IN") {
$q_string_where .= " " . $value . " ";
} else {
$q_string_where .= " '" . $value . "' ";
}
$q_string_orderby .= $q_string_where;
$sort_by = isset($_GET['s']) ? $_GET['s'] : false;
switch ($sort_by) {
case $tbfields_data;
break;
default:
$sort_by = 'DateCreated';
}
$q_string_orderby .= ' ORDER BY '.$sort_by.' ';
$direction = isset($_GET['d']) ? $_GET['d'] : false;
if ($direction != 'ASC' && $direction != 'DESC')
$direction = 'DESC';
$q_string_orderby .= $direction;
$res = $db->query($q_string_orderby);
$results = array();
if ($res) {
while ($r = mysql_fetch_assoc($res)) {
$results[] = $r;
}
}
$cache_key.="::" . $field_key . "::" . $operator . "::" . $value . "::" . $q_string_orderby;
}
$q_string .= $q_string_orderby;
}
$this_record = Formula::getLookupValue("formula_lookup_where_array", $this_get_table_form, $q_string, $cache_key);
array_push($GLOBALS['formula_executed_data_collector']['collected_form_id'], array(
"form_id" => $this_get_table_form['id'],
"where" => $q_string_where,
"function_name" => "Total",
"whole_query" => $q_string
));
$rslt = array_values(array_map(function($a) use($ReturnField) {
if (gettype($ReturnField) == "array") {
$array_collector = array();
foreach ($ReturnField as $key => $value) {
$array_collector[$value] = $a[$value];
}
return $array_collector;
} else if ($ReturnField == "*") {
return $a;
} else {
return $a[$ReturnField];
}
}, $this_record));
return $rslt;
}
}
I try to call a model from one of my Joomla controller but that doesn't seem to work.
class TieraerzteControllerDatatable extends JControllerLegacy
{
/**
* display task
*
* #return void
*/
function display($cachable = false)
{
// set default view if not set
$input = JFactory::getApplication()->input;
$model = $this->getModel('datatable');
$model->getTableData('grumpi_tieraerzte', 'id', array('id','name','strasse','telefon','fax'));
die();
}
}
In my model I placed a var_dump but it is not accessed. How can I debug my model call in controller?
I try to access the models return with the following url /administrator/index.php?option=com_tieraerzte&task=datatable.display&{arguments for the model}
trying to debug my codes piece by piece seems like the model is accessed and this code is causing the problem
// Paging
$sLimit = "";
if (isset(JRequest::getVar('iDisplayStart')) && JRequest::getVar('iDisplayLength') != '-1')
{
$sLimit = "LIMIT " . intval(JRequest::getVar('iDisplayStart')) . ", " . intval(JRequest::getVar('iDisplayLength'));
}
The whole method:
public function getTableData($table, $index_column, $columns)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Paging
$sLimit = "";
if (isset(JRequest::getVar('iDisplayStart')) && JRequest::getVar('iDisplayLength') != '-1')
{
$sLimit = "LIMIT " . intval(JRequest::getVar('iDisplayStart')) . ", " . intval(JRequest::getVar('iDisplayLength'));
}
// Ordering
$sOrder = "";
if (isset(JRequest::getVar('iSortCol_0')))
{
$sOrder = "ORDER BY ";
for ($i = 0; $i < intval(JRequest::getVar('iSortingCols')); $i++)
{
if (JRequest::getVar('bSortable_' . intval(JRequest::getVar('iSortCol_' . $i))) == "true")
{
$sortDir = (strcasecmp(JRequest::getVar('sSortDir_' . $i), 'ASC') == 0) ? 'ASC' : 'DESC';
$sOrder .= "`" . $columns[intval(JRequest::getVar('iSortCol_' . $i))] . "` " . $sortDir . ", ";
}
}
$sOrder = substr_replace($sOrder, "", -1);
if ($sOrder == "ORDER BY") {
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "";
if (isset(JRequest::getVar('sSearch')) && JRequest::getVar('sSearch') != "")
{
$like = '%' . JRequest::getVar('sSearch') . '%';
$sWhere = "WHERE (";
for ($i = 0; $i < count($columns); $i++)
{
if (isset(JRequest::getVar('bSearchable_' . $i)) && JRequest::getVar('bSearchable_' . $i) == "true")
{
$sWhere .= "`" . $columns[$i] . "` LIKE '" . $like . "' OR ";
}
}
$sWhere = substr_replace($sWhere, "", -3);
$sWhere .= ')';
}
// Individual column filtering
for ($i = 0; $i < count($columns); $i++)
{
if (isset(JRequest::getVar('bSearchable_' . $i)) && JRequest::getVar('bSearchable_' . $i) == "true" && JRequest::getVar('sSearch_' . $i) != '')
{
if ($sWhere == "")
{
$sWhere = "WHERE ";
} else {
$sWhere .= " AND ";
}
$sWhere .= "`" . $columns[$i] . "` LIKE ? " . $i . " ";
}
}
// SQL queries get data to display
$sQuery = "SELECT SQL_CALC_FOUND_ROWS `" . str_replace(" , ", " ", implode("`, `", $columns)) . "` FROM `" . $table . "` " . $sWhere . " " . $sOrder . " " . $sLimit;
$statement = $this->_db->prepare($sQuery);
// Bind parameters
if (isset(JRequest::getVar('sSearch')) && JRequest::getVar('sSearch') != "")
{
$statement->bind_param('s', $like);
}
for ($i = 0; $i < count($columns); $i++)
{
if (isset(JRequest::getVar('bSearchable_' . $i)) && JRequest::getVar('bSearchable_' . $i) == "true" && JRequest::getVar('sSearch_' . $i) != '')
{
$statement->bind_param('s' . $i, '%' . $_GET['sSearch_' . $i] . '%');
}
}
$db->setQuery($sQuery);
$res = $db->loadObjectList();
$rResult = array();
foreach ($res as $row)
{
$rResult[] = $row;
}
$iFilteredTotal = current($db->setQuery('SELECT FOUND_ROWS()')->loadResultArray());
// Get total number of rows in table
$sQuery = "SELECT COUNT(`" . $index_column . "`) FROM `" . $table . "`";
$iTotal = current($db->setQuery($sQuery));
// Output
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
// Return array of values
foreach ($rResult as $aRow)
{
$row = array();
array_push($row, '<input type="checkbox" id="someCheckbox" name="someCheckbox" />');
for ($i = 0; $i < count($columns); $i++)
{
//var_dump($aRow->$columns[$i]);
if ($columns[$i] != '')
{
$row[] = $aRow->$columns[$i];
}
}
array_push($row, '
<div class="btn-group" id="status">
<input type="button" class="btn b1" value="On">
<input type="button" class="btn b0 btn-danger" value="Off">
</div>
');
array_push($row, '
<div class="clearfix">
<div class="label label-important" style="padding:6px 9px; margin-right:5px"><span class="icon-trash"></span></div>
<div class="label label-success" style="padding:6px 9px"><span class="icon-cog"></span></div>
</div>
');
$output['aaData'][] = $row;
}
echo json_encode($output);
}
Make sure $model inside the controller is not null. If it's not null, than the problem is somewhere in the model's method called.
if $model is null, somehow the model you are calling is not loaded. Temporary try just to include the file with require_once JPATH_COMPONENT . '/models/datatable.php'
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);