/** * Query for point log entries based on $args * * @since 1.0 * @param array $args the query arguments * @return array of log entry objects */ public static function query($args) { global $wc_points_rewards, $wpdb; // calculate found rows? (costly, but needed for pagination) $found_rows = ''; if (isset($args['calc_found_rows']) && $args['calc_found_rows']) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } // distinct results? $distinct = ''; if (isset($args['distinct']) && $args['distinct']) { $distinct = 'DISTINCT'; } // returned fields $fields = "{$wc_points_rewards->user_points_log_db_tablename}.*"; if (!empty($args['fields']) && is_array($args['fields'])) { $fields .= ', ' . implode(', ', $args['fields']); } // joins $join = ''; if (!empty($args['join']) && is_array($args['join'])) { $join = implode(' ', $args['join']); } // where clauses $where = ''; if (!empty($args['where'])) { $where = "AND " . implode(" AND ", $args['where']); } // group by $groupby = ''; if (!empty($args['groupby']) && is_array($args['groupby'])) { $groupby = implode(', ', $args['groupby']); } // order by $orderby = ''; if (!empty($args['orderby'])) { // convert "really simple" format of simply a string if (is_string($args['orderby'])) { $args['orderby'] = array(array('field' => $args['orderby'])); } // check if the 'simple' format is being used with a single column to order by list($key) = array_keys($args['orderby']); if (is_string($key)) { $args['orderby'] = array($args['orderby']); } foreach ($args['orderby'] as $_orderby) { if (isset($_orderby['field'])) { $orderby .= empty($orderby) ? $_orderby['field'] : ', ' . $_orderby['field']; if (isset($_orderby['order'])) { $orderby .= ' ' . $_orderby['order']; } } } if ($orderby) { $orderby = 'ORDER BY ' . $orderby; } } // query limits $limits = ''; // allow a page and per_page to be provided, or simply per_page to limit to that number of results (defaults 'paged' to '1') if (!empty($args['per_page']) && empty($args['paged'])) { $args['paged'] = 1; } if (!empty($args['per_page'])) { $limits = ' LIMIT ' . ($args['paged'] - 1) * $args['per_page'] . ', ' . $args['per_page']; } // build the query $query = "SELECT {$found_rows} {$distinct} {$fields} FROM {$wc_points_rewards->user_points_log_db_tablename} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; $results = $wpdb->get_results($query); // record the found rows if (isset($args['calc_found_rows']) && $args['calc_found_rows']) { self::$found_rows = $wpdb->get_var('SELECT FOUND_ROWS()'); } $results = $results ? $results : array(); return $results; }