Cache API Calls - php

I have following code to call and echo some API calls from a site.
function popular_uploads() {
// If no saved data exists in the cache
if ($json_data === false) {
// Fetch new data from remote URL
$gameid = $instance['code1'];
$url = ("http://thegamesdb.net/api/GetGame.php?id=".$gameid."");
$json = file_get_contents($url);
$json_data = json_decode($json, false);
set_transient('my_unique_identifier', $json_data, 3600); $json_data = get_transient('my_unique_identifier');
}
foreach ( $json_data->items as $item ) {
$title=$item->Game->GameTitle;
$boxartw=$item->Game->Images->boxart[0];
$boxart=$item->Game->Images->boxart[1];
if ($boxart == NULL) {
$boxart = $boxartw;}
$publisher=$item->Game->Publisher;
$releasedate=$item->Game->ReleaseDate;
$newdate = date("d/m/Y", strtotime($releasedate));
$newday = date("d", strtotime($releasedate));
$newmon = date("m", strtotime($releasedate));
$newyear = date("Y", strtotime($releasedate));
echo '<div class="upcoming_games_side">';
echo '<div class="upcomig_bg"style="background-image:url(http://thegamesdb.net/banners/_gameviewcache/' .$boxart. ');></div>';
echo '<div class="dark-screen-uc"></div>';
echo '<img class="game-boxart_uc" alt="" src="http://thegamesdb.net/banners/_gameviewcache/'.$boxart.'"/>';
if ($title == null){
echo "N/A"; }else{
echo '<h1 class="title_uc">'.$title.'</h1>';}
if ($publisher == null){
echo "N/A"; }else{
echo '<p class="pub_uc">'.$publisher.'</p>';
}
if ($newdate == "01-01-1970"){
echo "N/A";
}else{
echo '<date class="date_uc">'.$newdate.'</date>';
}
$target = mktime(0, 0, 0, $newday, $newmon, $newyear) ;
$today = time () ;
$difference =($target-$today) ;
$days =(int) ($difference/86400) ;
if ($days == "0"){
echo "N/A"; }else{
echo '<date class="count_uc">'.$days.'</date>';}
echo '</div>';
}
}
But it's not working and doesn't Cache API data. So Where is my mistake and wahts part's of my code's are Wrong? I'd appreciate any help.
By the way, it's a Wordpress plugin.

Related

how to store json data in php use json_decode and for

I wrote a plugin for my site that is Ripley plugin
But when you copy the text to a user, it will be displayed as a code in the history
like this
{"action":"reply","umsg":"hi","uname":"admin","mymsg":"helo"}
The code I put in the history file is like this:
$jmsg = str_replace(array('<b>', '</b>', '<i>', '</i>'), '', $row['7']);
if (isJson($jmsg)) {
$jd = json_decode($jmsg, true);
if (isset($jd['action'])) {
$replymsg = $jd['umsg'];
$replyme = $jd['uname'];
$mymsg = $jd['mymsg'];
if ($jd['action'] == 'reply') {
if ($color == 'D5D5D7') {
$color = 'EEEEFF';
} else {
$color = 'D5D5D7';
}
echo "<msg><![CDATA[<tr id=\"msg-{$row['id']}\" bgcolor=\"#{$color}\"><td width=\"50\" align=\"center\">{$row['id']}{$delmsg}</td><td width=\"180\" align=\"center\">{$row['username']}</td><td width=\"80\" align=\"center\">" . jdate::start('Y/m/d H:i:s', $row['date']) . "</td><td align=\"center\" style=\"direction : rtl;word-break: break-all;max-width: 100px;font-family:{$row['fontname']};font-size:{$row['fontsize']}px;\"><div class=\"pmbox\"><div class=\"mess_back\"><div id=\"repbox\"><div id=\"khat\"><div id=\"name\">{$replyme}</div><div id=\"text\">{$replymsg}</div></div><div id=\"means\">{$mymsg}</div></div></div></div></td><td width=\"80\" align=\"center\">{$room}</td></tr>]]></msg>";
}
if ($jd['action'] == 'delete') {
continue;
}
if ($jd['action'] == 'reply') {
continue;
}
}
}
if ($color == 'D5D5D7') {
$color = 'EEEEFF';
} else {
$color = 'D5D5D7';
}
echo "<msg><![CDATA[<tr id=\"msg-{$row['id']}\" bgcolor=\"#{$color}\"><td width=\"50\" align=\"center\">{$row['id']}{$delmsg}</td><td width=\"180\" align=\"center\">{$row['username']}</td><td width=\"80\" align=\"center\">" . jdate::start('Y/m/d H:i:s', $row['date']) . "</td><td align=\"center\" style=\"direction : rtl;word-break: break-all;max-width: 100px;font-family:{$row['fontname']};font-size:{$row['fontsize']}px;\">{$row['text']}</td><td width=\"80\" align=\"center\">{$room}</td></tr>]]></msg>";
}

How to add a count == 0 to this?

I would like to add a count == 0 which if it is the case, just outputs 'please contact us to find out the dates', but I can't seem to get it to work. Please can someone advise?
$count = 0;
$your_repeater = get_field('add_date');
if ($your_repeater) {
while (have_rows('add_date')):
the_row();
$count++;
$my_field = get_sub_field('course_date');
if ($count == 0) {
echo 'please contact us to find out dates';
} else {
echo '';
}
if ($count == 1) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
// echo $my_field .', ';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>1. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo 'Contact us to find out more';
} else {
echo '';
}
}
if ($count == 2) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>2. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo '<img src="' .bloginfo('url').'/wp-content/themes/derbyskillbuild site/images/hourglass.png" />';
} else {
echo '';
}
}
if ($count == 3) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b> 3. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
} else {
echo '';
}
}
if ($count == 4) {
}
if ($count == 5) {
}
echo '</ul>';
endwhile;
}
It appears that you are checking the count way too soon in your code.
You start with a $count = 0;, but then in the while loop you first do $count++. So, at this point, the count is 1. Then a few lines later you check this:
if ($count == 0) {
echo 'please contact us to find out dates';
}
This will never return true, since you just did a $count++ from 0, so at this point it's always at least 1. It seems that this check should be outside of your while loop and you're currently closing the loop way too late.

Facebook php script doesn't work online

I have a FB script and it works fine locally but it doens't online.
The first script is een script for the events and the second one is to get de Facebook albums.
<?php
$fb_page_id = "408403535882715";
$access_token = "Acces_token";
$year_range = 10;
$since_date = date('Y-01-01', strtotime('-' . $year_range . ' years'));
$until_date = date('Y-01-01', strtotime('+' . $year_range . ' years'));
// unix timestamp years
$since_unix_timestamp = strtotime(date("Y-m-d"));
$until_unix_timestamp = strtotime($until_date);
$fields="id,name,description,location,venue,timezone,start_time,cover";
$json_link = "https://graph.facebook.com/{$fb_page_id}/events/feed/?fields={$fields}&access_token={$access_token}&since={$since_unix_timestamp}&until={$until_unix_timestamp}";
$json = file_get_contents($json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
// count the number of events
$event_count = count($obj['data']);
for($x=0; $x<$event_count; $x++){
if($x<1) {
$start_date = date( 'l, F d, Y', strtotime($obj['data'][$x]['start_time']));
$start_time = date('H:i', strtotime($obj['data'][$x]['start_time']) - 60 * 60 * 23);
$pic_big = isset($obj['data'][$x]['cover']['source']) ? $obj['data'][$x]['cover']['source'] : "https://graph.facebook.com/{$fb_page_id}/picture?type=large";
$eid = $obj['data'][$x]['id'];
$name = $obj['data'][$x]['name'];
$location = isset($obj['data'][$x]['location']) ? $obj['data'][$x]['location'] : "";
$description = isset($obj['data'][$x]['description']) ? $obj['data'][$x]['description'] : "";
echo "<div class='eventFrontpage'";
echo "<div class='info'>";
echo "<h1>{$name}</h1>";
echo "<span class='datum'>{$start_date} om {$start_time} uur</span></br>";
echo "<span class='locatie'>Locatie: {$location}</span></br>";
echo "<span class='content'>Info: {$description}</span></br>";
echo "</div>";
echo "</div>";
break;
}
}
?>
and this one (on different pages)
<?php
$fb_page_id = "408403535882715";
$json_link = "http://graph.facebook.com/{$fb_page_id}/albums?fields=id,name,description,link,cover_photo,count";
$json = file_get_contents($json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
$album_count = count($obj['data']);
for($x=0; $x<$album_count; $x++){
$id = $obj['data'][$x]['id'];
$name = $obj['data'][$x]['name'];
$description = $obj['data'][$x]['description'];
$link = $obj['data'][$x]['link'];
$cover_photo = $obj['data'][$x]['cover_photo'];
$count = $obj['data'][$x]['count'];
// if you want to exclude an album, just add the name on the if statement
if(
$name!="Profile Pictures" &&
$name!="Cover Photos" &&
$name!="Timeline Photos" &&
$name!="Mobile Uploads"
){
$show_pictures_link = "photos.php?album_id={$id}&album_name={$name}";
echo "<a class='mediaAlbum {$name}' href='{$link}' target='_blank'>";
echo "<img class='img-responsive' src='http://graph.facebook.com/{$cover_photo}/picture' alt=''>";
echo "<h2>{$name}</h2>";
echo "</a>";
}
}
?>
Someone an idea?
Answer: Because it was PHP < 5.4 on my server de code needed a translation :
$obj = json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $json), true);

Netbeans says PHP function has too many lines

I have a function and netbeans is saying I can only have 20 lines in my code.
Why is this and how could I fix this. I have another function with the same problem. Dreamweaver doesn't say anything so I don't know if this is a big problem.
my code:
function dispalyEvent($weekNr, $week, $year){
echo "<p>";
$gendate = new DateTime();
$gendate->setISODate($year,$week,$weekNr);
$month = $gendate->format('m');
$day = $gendate->format('d');
$event_query = mysql_query("SELECT * FROM calendar ORDER BY starttime");
while($event = mysql_fetch_array($event_query)) {
$startYear = $event['startyear'];
$startMonth = $event['startmonth'];
$startDay = $event['startdate'];
$endYear = $event['endyear'];
$endMonth = $event['endmonth'];
$endDay = $event['enddate'];
$period = new DatePeriod(
new DateTime($startYear.$startMonth.$startDay),
new DateInterval('P1D'),
new DateTime($endYear.$endMonth.$endDay +1)
);
$currentDate = $year."-".$month."-".$day;
foreach ($period as $savedDate) {
if ($currentDate == $savedDate->format('Y-m-d')){
if ($event['Approved'] == "Approved"){
echo "</p>";
echo "<p>";
if ($event['ad']) {
echo "<img src='images/".$event['ad']."' alt='event-ad' width='300' height='100' />";
} else { echo " "; }
echo "</p>";
echo "<p> </p>";
echo "<div class='toggleLink' style='cursor: pointer; color: #333;'>";
echo $event['starttime']." ".$event['title'];
echo "</p>";
echo "</div>";
echo " <div class='toggle'>";
echo "<p class='toggleLink'>";
echo "(".$event['starttime']."-".$event['endtime'].") ".$event['location']." - ".$event['address']." - Admission Price: $".$event['price']."<br>".$event['description'];
echo "</div>";
}}}}
echo "</p>";
}
?>

How to move page to the required path?

I make a php page in which i get data from bar but when i click cmd=7 and mode=test it moves cmd=default,how i set the links to the desired pages.
Here is my code:
function default1(){
$mode=$_GET['mode'];
if($mode=='')
{
$mode=$_POST['mode'];
}
$dates = array();
$timestamp = strtotime('-30 days');
for ($i = 0 ; $i <=30 ; $i++) {
//insert the date
$dates[$i]= date('m-d-Y', $timestamp);
//increase the day
$timestamp += 24 * 3600;
}
//print_r ($dates);
$strQuery="select DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y') as transaction_date,sum(amount)as Amount from transactions where mode='".$mode."' group by DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y')";
$result = $GLOBALS ['mysqli']->query ($strQuery) or die ($GLOBALS ['mysqli']->error . __LINE__);
while($rs=$result->fetch_assoc ())
{
$res[]=$rs;
}
//print_r ($res);
$strXML = "<chart caption='Reports of transactions' xAxisName='Date' yAxisName='Amount' showValues='0' useRoundEdges='1' palette='3'>";
for ($i = 0 ; $i <=30 ; $i++) {
foreach($res as $r)
{
if($r['transaction_date']==$dates[$i]){
$str = $r['transaction_date'];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='" .$r['Amount']."' />";
break;
}
else {
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
}
$strXML .=$substrXML;
}
$strXML .= "</chart>";
return $strXML;
}
function past7days(){
//$mode=$_GET['mode'];
//if($mode=='')
//{
//$mode=$_POST['mode'];
//}
$dates = array();
$timestamp = strtotime('-7 days');
for ($i = 0 ; $i <=7 ; $i++) {
$dates[$i]= date('m-d-Y', $timestamp);
$timestamp += 24 * 3600;
}
$strQuery="select DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y') as transaction_date,sum(amount)as Amount from transactions WHERE transaction_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() and mode='".$mode."' group by DATE_FORMAT(transactions.transaction_date,'%m-%d-%Y')
";
$result = $GLOBALS ['mysqli']->query ($strQuery) or die ($GLOBALS ['mysqli']->error . __LINE__);
while($rs = $result->fetch_assoc ())
{
$res[]=$rs;
}
$strXML = "<chart caption='Reports of transactions' xAxisName='Date' yAxisName='Amount' showValues='0' useRoundEdges='1' palette='3'>";
for ($i = 0 ; $i <=7 ; $i++) {
if(mysqli_num_rows($result)>0){
foreach($res as $r)
{
if($r['transaction_date']==$dates[$i]){
$str = $r['transaction_date'];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML.="<set label='".$transactiondate."' value='".$r['Amount']."' />";
break;
}
else {
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
}
}
else{
$str=$dates[$i];
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
$transactiondate=$dateObj->format('M d');
$substrXML = "<set label='".$transactiondate."' value='0' />";
}
$strXML .=$substrXML;
}
$strXML .= "</chart>";
return $strXML;
}
if($_GET['cmd']=='' || $_GET['cmd']=='default' )
{
?>
<? echo date('M jS Y' ,strtotime($startdate)); ?> to <? echo date('M jS Y' ,strtotime($enddate)); ?>
<?
}
else
{
?>
<? echo date('M jS Y' ,strtotime($startdate)); ?> to <? echo date('M jS Y' ,strtotime($enddate)); ?>
<?
}
if($_GET['cmd']=='7')
{
?>
<span style="margin-left:10px;">Past 7 Days</span>
<?
}
else
{
?>
Past 7 Days
<?
try it
if($_GET['cmd']=='' || $_GET['cmd']=='default' )
{
echo date('M jS Y' ,strtotime($startdate))." To ".date('M jS Y' ,strtotime($enddate));
}
else
{
$url = "merchant/products/1/manage/reports?cmd=default&mode=".$_GET['mode'];
header("location:".$url);
exit;
}
if($_GET['cmd']=='7')
{
echo '<span style="margin-left:10px;">Past 7 Days</span>';
}
else
{
$url = "merchant/products/1/manage/reports?cmd=7&mode=".$_GET['mode'];
header("location:".$url);
exit;
}
<script type="text/javascript">
document.location.href = '/merchant/products/1/manage/reports?cmd=7&mode=<?php echo $_GET["mode"]; ?>';
</script>

Categories