cron lock table each 5 minutes - php

Each 5,10,60,3600 minutes crons are runned,
When i check errorlog i see very much deadlocks exceptions, almost each 5 minutes cron send deadlock, timeout and serialization errors to log.
If i understand good deadlocks are happened when two or more queries using same table, what is very possible in my code.
I am using table MAP 2 times in each cron, because i need to map each team,
for example:
Chelsea after mapping returns Chelsea FC
Everton after mapping returns Everton FC
I am getting teams from large xml files, when i kill all processes cron5 is runned in 2 minutes what is ok, but when other processes are on, it takes so while...
When i check by SHOW OPEN TABLES WHERE in_use>0 i see
map table in_use mostly 2, sometimes 1.
function getMap($country,$data){
//echo $data . '<br>';
$fdata = $data;
$query = $this->PDO->prepare("CALL GetMap(:data)");
$query->bindParam(':data', $fdata);
$query->execute();
//echo 'DATA: ' . $data. ' RES: '.$res . '<br>';
$res = $query->fetchColumn();
if($res!=''){
$query->closeCursor();
$sql = "UPDATE map SET Country = :country WHERE Base = :base";
$q2 = $this->PDO->prepare($sql);
$q2->bindParam(':country', $country);
$q2->bindParam(':base', $res);
$q2->execute();
//echo $res;
return $res;
}
else
{
$query->closeCursor();
$this->fillMap($country,$fdata);
return $fdata;
}
}
and this is procedure for GetMap
DELIMITER //
CREATE PROCEDURE GetMap(p_team VARCHAR(100))
BEGIN
SELECT Base FROM map WHERE
map.Base = p_team OR
Ver1 = p_team OR
Ver2 = p_team OR
Ver3 = p_team OR
Ver4 = p_team OR
Ver5 = p_team OR
Ver6 = p_team OR
Ver7 = p_team OR
Ver8 = p_team OR
Ver9 = p_team OR
Ver10 = p_team OR
Ver11 = p_team OR
Ver12 = p_team;
end //
DELIMITER ;
Now my question is how to UNLOCK table map when that table is locked using php?
Also i need to say that i start transaction before xml reading, and commit when everything is completed, so transaction wait about 2 minutes when probably map is not locked. That is maybe reason why i get timeout errors, i can move it inside loop or change mysql timeout.
EDIT detailed code:
CHECK $this->getMap(); what is mostly used table.
function sendOddsToDb(){
try{
$this->conn->connect();
$this->PDO->beginTransaction();
$countries = $this->OddCountries;
$stmt = $this->PDO->prepare($this->insOdds);
//$dbempty = $this->countRows('odds');
//$this->clrLeagues();
foreach($countries as $country){
$path = "{$this->base}/feeds/odds/{$country}odds.xml";
$odds_feed = $this->parser->parseFile($path);
$fupddate = date('Y-m-d H:i:s',strtotime($odds_feed->attributes()->updated));
$newcountry = '';
if(isset($odds_feed->league)){
$newcountry = $odds_feed->league->attributes()->country;
$fcountries = $this->filterCountries($newcountry);
echo $fcountries . '<br>';
$sql = "select UpdatedDate from odds where Country = '{$fcountries}' order by UpdatedDate desc limit 1";
$res = $this->PDO->query($sql);
$dbupd = date('Y-m-d H:i:s',strtotime($res->fetchColumn()));
if(!$this->sameUpdated($fupddate,$dbupd)){
foreach($odds_feed->league as $league){ //za svaku ligu u fidu
$subid = $league->attributes()->sub_id;
$sportname = '';
$sportid = 0;
if($odds_feed->attributes()->sport == 'soccer' || $odds_feed->attributes()->sport == 'football'){
$sportname = 'football';
$sportid = 1;
}
else{
$sportname = NULL;
}
$lg2 = '';
$lg = $league->attributes()->name;
$ctr = $league->attributes()->country.':';
if(!contains(strtolower($lg),strtolower($ctr))){
$lg2 = ucfirst($ctr) . ' ' . ucfirst($lg);
}
else{
$lg2 = $league->attributes()->name;
}
$flg = $this->getMap2($lg2);
$this->sendLeaguesToDb($league->attributes()->id, $flg ,$fcountries,$sportid,$subid,'tipgin');
foreach($league->match as $match){
$dbdate = date('Y-m-d',strtotime($match->attributes()->date));
$updateddate = date('Y-m-d H:i:s',strtotime($odds_feed->attributes()->updated));
$dbtime = date('H:i:s', strtotime($match->attributes()->time));
$datetime = date('Y-m-d H:i:s',strtotime($dbdate . $dbtime));
$hteam = $this->getMap($fcountries,toShort($match->home->attributes()->name));
$ateam = $this->getMap($fcountries,toShort($match->away->attributes()->name));
//echo $hteam . ' ' . $ateam;
$fixid = 0;
if($match->attributes()->id == 0 || $match->attributes()->id == ''){
if($match->attributes()->alternate_id == 0 || $match->attributes()->id == ''){
$fixid = $match->attributes()->alternate_id_2;
}
else{
$fixid = $match->attributes()->alternate_id;
}
}
else{
$fixid = $match->attributes()->id;
}
//$m = $hteam . ' ' . $ateam;
//var_dump('MATCH: ' . $m . ' HTEAM: ' . mb_detect_encoding($hteam). ' ATEAM: ' . mb_detect_encoding($ateam));
if($match->odds != NULL or $match->odds != ''){
foreach ($match->odds as $odds) {
//var_dump($odd);
if($odds->type != NULL or $odds->type != ''){
foreach ($odds->type as $type) {
if($type->bookmaker != NULL or $type->bookmaker != ''){
foreach ($type->bookmaker as $bookmaker) {
//$oldbook = ;
if($bookmaker->attributes()->name != 'BetClick'){
if($bookmaker->attributes()->name != 'Bodog'){
if($bookmaker->attributes()->name != 'YouWin'){
$homeodds = NULL;
$drawodds = NULL;
$awayodds = NULL;
$numodds = NULL;
$dbhandicap = NULL;
$id2 = '0';
$typename = $this->getMap2($type->attributes()->name);
$fbooks = $this->filterBooks($bookmaker->attributes()->name);
if($typename == 'Over/Under' || $typename == 'Over/Under 1st Half' || $typename == 'Over/Under 2nd Half'){
foreach ($bookmaker->total as $total) { //daj kvote za svaki mec
$numodds = $total->attributes()->name;
foreach($total->odd as $odd){
switch ($odd->attributes()->name) {
case 'Over':
$homeodds = $odd->attributes()->value;
break;
case 'Under':
$awayodds = $odd->attributes()->value;
break;
}
$id2 = $numodds;
}
//echo "HOME TEAM: {$hteam} <BR>";
//echo "AWAY TEAM: {$ateam} <BR>";
/*
echo 'IF ID: ' . $match->attributes()->alternate_id_2 . $league->attributes()->country . " ODDS: {$homeodds} {$drawodds} {$awayodds} TYPE: {$typename} BOOK: {$fbooks} ID2: {$id2}" . "<br>";
*/
$this->execOdds($stmt, $fixid, $updateddate,
$typename, $fcountries,$league->attributes()->name,
$league->attributes()->id, $subid, $league->attributes()->cup,$sportname,
$hteam,$match->home->attributes()->id,
$ateam,$match->away->attributes()->id, $datetime, $dbdate,
$dbtime, $match->attributes()->status, $numodds,$homeodds,$drawodds,
$awayodds, $fbooks, $bookmaker->attributes()->id, $dbhandicap, $id2);
}
}
else if($typename == 'Handicap' || $typename == '3Way Handicap'){
$homeodds = array();
$drawodds = array();
$awayodds = array();
$arrhandicap = array();
$fhandicap = '';
foreach ($bookmaker->handicap as $handicap) { //daj kvote za svaki mec
if (strpos($handicap->attributes()->name,'+') !== false) {
$fhandicap = str_replace('+','',(string)$handicap->attributes()->name);
}else{
$fhandicap = (string)$handicap->attributes()->name;
}
$newhandi = '';
foreach($handicap->odd as $odd){
//$odd = $handicap->odd;
switch ($odd->attributes()->name) {
case '1':
$newhandi = (string)$fhandicap;
$homeodds[(string)$newhandi] =
(string)$odd->attributes()->value;
break;
case 'X':
$newhandi = $fhandicap;
$drawodds[(string)$newhandi] =
(string)$odd->attributes()->value;
break;
case '2':
if (strpos($fhandicap,'-') !== false) { //if negative
$newhandi = str_replace('-','',(string)$fhandicap); //to positive
//echo 'NEGATIVE - OLD: ' . $fhandicap . ' NEW: '.$newhandi . '<br>';
}
elseif($fhandicap=='0'){
$newhandi = '0';
}
else{ //if positive
$newhandi = '-' . (string)$fhandicap; //to negative
//echo 'POSITIVE - OLD: ' . $fhandicap . ' NEW: '.$newhandi . '<br>';
}
$awayodds[(string)$newhandi] = (string)$odd->attributes()->value;
break;
}
$arrhandicap[] = (string)$newhandi;
}
}
//print_r($arrhandicap);
//$arrhandicap[] = sort($dbhandicap);
$inhand = '';
$varhome = '';
$vardraw = '';
$varaway = '';
foreach($arrhandicap as $hand){
$inhand = (string)$hand;
if(isset($hand)){
//echo $typename. ': ' . $hand . '<br>';
if((array_key_exists($inhand,$homeodds)) && (isset($homeodds[$inhand]))){
$varhome = $homeodds[$inhand];
}
if((array_key_exists($inhand,$awayodds)) && (isset($awayodds[$inhand]))){
$varaway = $awayodds[$inhand];
}
if((array_key_exists($inhand,$drawodds)) && (isset($drawodds[$inhand]))){
$vardraw = $drawodds[$inhand];
}
$this->execOdds($stmt, $fixid, $updateddate,
$typename, $fcountries,$league->attributes()->name,
$league->attributes()->id, $subid, $league->attributes()->cup,$sportname,
$hteam,$match->home->attributes()->id,
$ateam,$match->away->attributes()->id, $datetime, $dbdate,
$dbtime, $match->attributes()->status, $numodds,$varhome,
$vardraw,$varaway, $fbooks,
$bookmaker->attributes()->id, $hand, $hand);
/*echo 'ELSEIF ID: ' . $match->attributes()->id . $league->attributes()->country . " HOMEODDS: {$varhome} DRAW: {$vardraw} AWAYODDS: {$varaway} TYPE: {$typename} BOOK: {$fbooks} ID2: {$inhand}" . "<br>";
*/}
}
}
else{
foreach ($bookmaker->odd as $odd) { //daj kvote za svaki mec
if($typename == 'Home/Away'){
$typename = 'Draw No Bet';
}
switch ($odd->attributes()->name) {
case '1':
case '1X':
case 'Yes':
$homeodds = $odd->attributes()->value;
break;
case 'X':
case 'X2':
$drawodds = $odd->attributes()->value;
break;
case '2':
case '12':
case 'No':
$awayodds = $odd->attributes()->value;
break;
}
$id2 = 0;
//echo 'ID: ' . $match->attributes()->alternate_id_2 . $league->attributes()->country . " ODDS: {$homeodds} {$drawodds} {$awayodds} TYPE: {$typename} BOOK: {$fbooks} ID2: {$id2}" . "<br>";
}
/*
echo "ELSE HOME TEAM: {$hteam} <BR>";
echo "ELSE AWAY TEAM: {$ateam} <BR>";
*/
$this->execOdds($stmt, $fixid, $updateddate,
$typename, $fcountries,$league->attributes()->name,
$league->attributes()->id, $subid, $league->attributes()->cup,$sportname,
$hteam,$match->home->attributes()->id,
$ateam,$match->away->attributes()->id, $datetime, $dbdate,
$dbtime, $match->attributes()->status, $numodds,$homeodds,$drawodds,
$awayodds, $fbooks, $bookmaker->attributes()->id, $dbhandicap, $id2);
}
}
}
}
}
}
}
}
}
}
}
}
}
//echo $country.'<br>';
}
}
$this->PDO->commit(); //SAVE
$this->conn->close();
}
catch(Exception $e){
//echo $e;
}
}
private function execOdds($stmt, $matchid, $upddate, $type, $country, $league, $leagueid, $subid, $cup, $sport, $hteam, $hteamid, $ateam, $ateamid, $datetime, $date, $time, $status, $numodds, $homeodds, $drawodds, $awayodds, $book, $bookid, $handicap, $id2){
$event = $hteam . ' - ' . $ateam;
$fcountry = $country;
$fleague = $league;
$stmt->bindParam(':fixturematchid', $matchid);$stmt->bindParam(':updateddate',$upddate);$stmt->bindParam(':type',$type);
$stmt->bindParam(':country',$fcountry);$stmt->bindParam(':league',$fleague);$stmt->bindParam(':leagueid',$leagueid);
$stmt->bindParam(':subid',$subid);
$stmt->bindParam(':cup',$cup);$stmt->bindParam(':eventname',$event);$stmt->bindParam(':sportname',$sport);
$stmt->bindParam(':hometeam', $hteam);$stmt->bindParam(':hometeamid', $hteamid);$stmt->bindParam(':awayteam', $ateam);
$stmt->bindParam(':awayteamid', $ateamid);$stmt->bindParam(':datetime',$datetime);$stmt->bindParam(':date',$date);
$stmt->bindParam(':time',$time);$stmt->bindParam(':status',$status);$stmt->bindParam(':numodds', $numodds);
$stmt->bindParam(':homeodds', $homeodds);$stmt->bindParam(':drawodds',$drawodds);$stmt->bindParam(':awayodds',$awayodds);
$stmt->bindParam(':bookmaker',$book);$stmt->bindParam(':bookmakerid',$bookid);$stmt->bindParam(':handicap', $handicap);
$stmt->bindParam(':id2', $id2);
$stmt->execute(); //EXEC*/
}

Related

Returning JSON from a PHP function

I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));

How to add more elements to specific key in array?

I am trying to convert xml node into array, i have 3 separated nodes inside parent match node, so i need to convert all them into array.
When i try this code
foreach($lineup->away->player as $player){
$awaysquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
and call this matcharr by:
print_r($matcharr);
There is just last element for each index/array, i want to get all players from lineup tag.
So print_r prints this:
Array ( [goal] => 2456166 [name] => Luís Leal [number] => 9 [playerid]
=> 2474225 [yellow] => 2486288 [subin] => 2353344 [subout] => 0 [minute] => NA )
for each match tag, but i need to get 22 players for each match.
Here is more detailed code:
foreach($week->match as $match){
$matcharr = array();
//var_dump($match);
$fixid = 0;
if($match->attributes()->id == 0 || $match->attributes()->id == ''){
if($match->attributes()->alternate_id == 0 || $match->attributes()->id == ''){
$fixid = $match->attributes()->alternate_id_2;
}
else{
$fixid = $match->attributes()->alternate_id;
}
}
else{
$fixid = $match->attributes()->id;
}
$dbdate = date('Y-m-d',strtotime($match->attributes()->date));
$dbtime = date('H:i:s', strtotime($match->attributes()->time));
//if($dbdate == date('Y-m-d')){
echo $dbdate . ' ' . date("Y-m-d");
$datetime = date('Y-m-d H:i:s',strtotime($dbdate . $dbtime));
$fcountry = $this->filterCountries($results->attributes()->country);
$stadium = $match->attributes()->venue;
$city = $match->attributes()->venue_city;
//echo $fcountry;
//$home = $match->home->attributes()->name;
//$away = $match->away->attributes()->name;
$home = '';
$away = '';
$homeid = 0;
$awayid = 0;
$hgoals = 0;
$agoals = 0;
if($match->home){
$home = $this->getMap($fcountry,$match->home->attributes()->name);
$away = $this->getMap($fcountry,$match->away->attributes()->name);
$homeid = $this->filterTeams($fcountry,$match->home->attributes()->id);
$awayid = $this->filterTeams($fcountry,$match->away->attributes()->id);
$hgoals = $match->home->attributes()->score;
$agoals = $match->away->attributes()->score;
}
$eventname = $home . ' - ' . $away;
$halftimehomegoals = 0;
$halftimeawaygoals = 0;
if($match->halftime->attributes()->score != NULL){
$halftime = explode("-",$match->halftime->attributes()->score);
$halftimehomegoals = (int)$halftime[0];
if(array_key_exists(1,$halftime)){
$halftimeawaygoals = (int)$halftime[1];
}
}
$homescore = '';
$awayscore = '';
if($match->goals->goal != NULL){
foreach($match->goals->goal as $goal){
if($goal->attributes()->team == 'home'){
$homescore .= $goal->attributes()->minute.': '.
$goal->attributes()->player.'; ';
$matcharr['goal'] = (int)$goal->attributes()->playerid;
}
elseif($goal->attributes()->team == 'away'){
$awayscore .= $goal->attributes()->player.'; ';
$matcharr['goal'] = (int)$goal->attributes()->playerid;
}
}
}
$homesquad = '';
$awaysquad = '';
if($match->lineups != NULL){
foreach($match->lineups as $lineup){
if($lineup->home->player != NULL){
foreach($lineup->home->player as $player){
$homesquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
}
if($lineup->away->player != NULL){
foreach($lineup->away->player as $player){
$awaysquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
}
}
}
$homesub = '';
$awaysub = '';
if($match->substitutions != NULL){
foreach($match->substitutions as $subs){
if($subs->home->substitution != NULL){
foreach($subs->home->substitution as $sub){
$homesub .= $sub->attributes()->minute."' in: ".
$sub->attributes()->player_in_name . '; ' . ' out: ' .
$sub->attributes()->player_out_name . '; ';
$matcharr['subin'] = (int)$sub->attributes()->player_in_id;
$matcharr['subout'] = (int)$sub->attributes()->player_out_id;
$matcharr['minute'] = (string)$sub->attributes()->minute;
}
}
if($subs->away->substitution != NULL){
foreach($subs->away->substitution as $sub){
$awaysub .= $sub->attributes()->minute."' in: ".
$sub->attributes()->player_in_name . '; ' .
$sub->attributes()->player_out_name . '; ';
$matcharr['subin'] = (int)$sub->attributes()->player_in_id;
$matcharr['subout'] = (int)$sub->attributes()->player_out_id;
$matcharr['minute'] = (string)$sub->attributes()->minute;
}
}
}
}
echo $leaguename . ' ' . $leagueid . ' ' . $fixid . ' ' . $eventname.'<br>';
print_r($matcharr);
Add some counter variable before storing it in array like below
$element_count = 0;//Counter variable
foreach ($lineup->away->player as $player) {
$awaysquad .= $player->attributes()->name . '; ';
$matcharr[$element_count]['name'] = (string)$player->attributes()->name;
$matcharr[$element_count]['number'] = (int)$player->attributes()->number;
$matcharr[$element_count]['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ", $player->attributes()->booking));
if (substr_count($player->attributes()->booking, "YC") == 1) {
$matcharr[$element_count]['yellow'] = (int)$player->attributes()->id;
}
elseif ((substr_count($player->attributes()->booking, "RC") == 1) or ($yellowcount == 3)) {
$matcharr[$element_count]['red'] = (int)$player->attributes()->id;
}
$element_count++;
}

Styling Dynamically created selection drop box using HTML and CSS. How?

This code is in php file. How I will style tag with "Select Size" and customize the drop down section. Below is one div which i want to style but ht class is created dynamically. And here div drop box are created dynamically and the data entered is also been done dynamically. HELP
$i = 0;
$attribArr = array();
$sizeArr = array();
$colorArr = array();
$colorStr = "color";
$sizeStr = "size";
$phpArray = array(
0 => 001 - 1234567,
1 => 1234567,
2 => 12345678,
3 => 12345678,
4 => 12345678
);
foreach ($order['cart_items'] as $item) {
$i++;
$cssNo = $i % 5;
if ($cssNo == 0) {
$cssNo = 5;
}
$giftcss = "gift-info gift" . $cssNo;
// Get products description
$presult = array();
$productId = $item['product_id'];
$reslt = getProductOptions($productId);
$values = $reslt['values'];
info('option type=' . $reslt['type'] . ' Name=' . $reslt['name']);
$sizeOptionValues = '<option>';
$colorOptionValues = '<option>';
if ($reslt['name'] == 'Size') {
foreach ($values as $value) {
info('vl=' . $value['options_value_name']);
$sizeOptionValues.= str_replace(' ', '', $value['options_value_name']) . '</option><option>';
}
}
if ($reslt['name'] == 'Color') {
foreach ($values as $value) {
info('vl=' . $value['options_value_name']);
$colorOptionValues.= $value['options_value_name'] . '</option><option>';
}
}
$pquery = "SELECT products_description, pr.products_image, products_name FROM "
. TABLE_PRODUCTS_DESCRIPTION . " AS pd JOIN " . TABLE_PRODUCTS . " as pr ON pr.products_id = pd.products_id WHERE pd.products_id=" . $productId;
$presult = $db->Execute($pquery);
$product_name = $presult->fields['products_name'];
$product_image = $presult->fields['products_image'];
$product_desc = $presult->fields['products_description'];
$prodImgs = explode(".", $product_image);
$prodImg0 = $prodImgs[0];
$prodImgExt = $prodImgs[1];
$prod_img_name = $prodImg0 . 'v.' . $prodImgExt;
info("getOrder", "Product Name=" . $product_name . " prod image=" . $prod_img_name);
$prod_desc_url = EL_PROD_DESC_PATH . $productId;
$prodAttrQry = "SELECT * FROM " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " WHERE products_prid = " . $productId . " AND orders_id = " . $orderId;
$attrReslt = $db->Execute($prodAttrQry);
$color = false;
$colorValue = '';
$size = false;
$sizeValue = '';
$personalised = false;
$attr = false;
$personalisedMsg = '';
if ($attrReslt->RecordCount() > 0) {
$attr = true;
$attrArr = array();
while (!$attrReslt->EOF) {
$optName = $attrReslt->fields['products_options'];
$optValue = $attrReslt->fields['products_options_values'];
if ($optName == 'Size') {
$size = true;
$sizeValue = $optValue;
} else if ($optName == 'Color') {
$color = true;
$colorValue = $optValue;
} else if ($optName == '') {
$personalised = true;
$rslt = explode(".", $optValue);
if ((isset($rslt[1]) && $rslt[1] == 'jpg') || (isset($rslt[1]) && $rslt[1] == 'png')) {
$personalisedMsg = "<b>Uploaded Image</b> " . "<br><img style = 'width:200px; height:200px;'src = '$optValue'/>";
} else {
$personalisedMsg = '<b>Personal Message</b><br>' . $optValue;
}
}
$sizeArr[$i] = $sizeValue;
$colorArr[$i] = $colorValue;
$attribArr['personalise_val' . $i] = $personalisedMsg;
$attrReslt->MoveNext();
}
}
$colorVisibility = 'none';
$sizeVisibility = 'none';
$personalisedVisib = 'none';
$headlineVisib = 'none';
if ($color) {
$colorVisibility = 'inline';
$headlineVisib = 'inline';
}
if ($size) {
$sizeVisibility = 'inline';
$headlineVisib = 'inline';
}
if ($personalised) {
$personalisedVisib = 'inline';
}
$secondScreen .= <<
<div class="{$giftcss}">
<input type="hidden" name= "product_id{$i}" value="{$productId}"/>
<div class="gift-img"><img src="http://{$domainName}/gifts/images/{$prod_img_name}" height="250"></div>
<div class="divider"></div><div class="gift-desc"><h3>{$product_name}</h3><span>{$product_desc}</span></div>
<div style="width:100%;"><h3 style="display:{$headlineVisib}">Customize your gift</h3><br>
<p style="display:{$sizeVisibility};">Select Size<select id = "prod_size{$i}" name="prod_size{$i}" >{$sizeOptionValues}</select></p>
<p style="display:{$colorVisibility};">Select Color<select id = "prod_color{$i}" name="prod_color{$i}" >{$colorOptionValues}</select></p>
<p style="display:{$personalisedVisib};">{$personalisedMsg}</p></div>
MARKUP;
$secondScreen .= <<<MARKUP
Im not entirely sure what you mean? But if it's what I think you mean. To print out your php values into the class='' attribute you would:
<div class="<?php echo $giftcss; ?>">
<input type="hidden" name= "product_id<?php echo $i; ?>" value="{$productId}"/>
<div class="gift-img">
<img src="http://<?php echo $domainName; ?>/gifts/images/<?php echo $prod_img_name; ?>" height="250"></div>
Simply <?php echo $variable; ?> into each html attribute.

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";

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