Facebook php script doesn't work online - php

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

Related

Get icon from XML URL

I am creating some EPG for the website. I do not have experience. Unfortunately, I'm finding it difficult. How can I get the icons, what is wrong in this code?`
Final code working:
<?php
$url = 'XML URL LINK';
$xml=simplexml_load_file("$url");
$progs = $xml->xpath('//programme');
foreach ($progs as $prog) {
$title = $prog->xpath('./title/text()')[0];
$link = (count($prog->xpath('./icon/#src'))>0) ? ($prog->xpath('./icon/#src'))[0] : ("No icon");
echo "Logo: <img src='{$link}'> <br/>" ;
echo "Title : ".$title. "<br>";
echo "<br>";
}
?>
If I understand you correctly, something like this should get you close to what I think you are trying to do. Note that not all programs have associated logos.
$progs = $xml->xpath('//programme');
foreach ($progs as $prog) {
$title = $prog->xpath('./title/text()')[0];
$link = (count($prog->xpath('./icon/#src'))>0) ? ($prog->xpath('./icon/#src'))[0] : ("No icon");
echo($title .": ". $link);
echo "\r\n";
}
EDIT:
I'm still not entirely sure I understand what you want, but it sounds like you need to wrap the whole thing in html and output to a browser. Something like:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$url = 'https://raw.githubusercontent.com/HelmerLuzo/TDTChannels_EPG/master/TDTChannels_EPG.xml';
$xml=simplexml_load_file("$url");
$progs = $xml->xpath('//programme');
foreach ($progs as $prog) {
$title = $prog->xpath('./title/text()')[0];
$link = (count($prog->xpath('./icon/#src'))>0) ? ($prog->xpath('./icon/#src'))[0] : ("No icon");
echo "Logo: <img src='{$link}'> <br/>" ;
echo "Title : ".$title. "<br>";
echo "<br>";
}
?>
</body>
</html>
This was a fun one. This uses a known hack to convert the xml into an array using json_decode and json_encode, this makes it easier to work with in my opinion. It also makes extensive use of the DateTime object.
$url = 'https://raw.githubusercontent.com/HelmerLuzo/TDTChannels_EPG/master/TDTChannels_EPG.xml';
$xml = simplexml_load_file($url);
$xml = json_decode(json_encode($xml), true); // Hack so we don't have to cast values in the future
// https://www.php.net/manual/en/timezones.php
$originalTimezone = 'Europe/Madrid';
$changeTimezone = 'Australia/Sydney'; // If empty, will not change timezone
//$outputFormat = 'Y-m-d H:i:s O';
$outputFormat = 'G:i';
$channels = [];
foreach ($xml['channel'] as $channel) {
$id = $channel['#attributes']['id'];
$channels[$id]['Display Name'] = $channel['display-name'];
$channels[$id]['Now Showing'] = [];
}
$now = new DateTime('now', new DateTimeZone($originalTimezone));
$programmes = [];
foreach ($xml['programme'] as $programme) {
$id = $programme['#attributes']['channel'];
$start = $programme['#attributes']['start'];
$start = DateTime::createFromFormat('YmdHis O', $start);
if (!empty($changeTimezone))
$start = $start->setTimezone(new DateTimeZone($changeTimezone));
$stop = $programme['#attributes']['stop'];
$stop = DateTime::createFromFormat('YmdHis O', $stop);
if (!empty($changeTimezone))
$stop = $stop->setTimezone(new DateTimeZone($changeTimezone));
if ($start < $now && $now < $stop) {
$nowShowing = [
'Title' => $programme['title'],
'Subtitle' => '',
'Description' => '',
'Date' => '',
'Start' => '',
'Stop' => '',
'Icon' => '',
];
if (isset($programme['sub-title']))
$nowShowing['Subtitle'] = $programme['sub-title'];
if (isset($programme['desc']))
$nowShowing['Description'] = $programme['desc'];
if (isset($programme['date']))
$nowShowing['Date'] = $programme['date'];
if (isset($programme['date']))
$nowShowing['Icon'] = $programme['icon']['#attributes']['src'];
$nowShowing['Start'] = $start->format($outputFormat);
$nowShowing['Stop'] = $stop->format($outputFormat);
$channels[$id]['Now Showing'] = $nowShowing;
}
}
foreach ($channels as $id => $details) {
echo $details['Now Showing']['Start'] . ' - ' . $details['Now Showing']['Stop'] . '<br>' .
'Channel:' . $details['Display Name'] . '<br>' .
'Title: ' . $details['Now Showing']['Title'] . '<br>' .
'Info: ' . $details['Now Showing']['Subtitle'] . '<br>' .
'Description: ' . $details['Now Showing']['Description'] . '<br>' .
'Logo: <img src="'.$details['Now Showing']['Icon'].'"/><br><br>';
}

Cache API Calls

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.

How to search defined class or variable's location

These errors keep coming after changing the PHP website to new server.
1st - Solved by "shaddy"
Notice: Undefined variable: es in /home/musthand/public_html/external/site/header.php on line 2
<?php
if(!is_object($es))
{
require_once('includes/EliteScript.php');
$es = new EliteScript();
$sMemberId = $es->getMemberId();
}
// Get the base URL
$sBaseUrl = $es->getConfig('baseUrl');
$sImageUrl = $es->getConfig('imageUrl');
$sMemberId = $es->getMemberId();
$sUsername = $es->getMemberUsername($sMemberId);
$sIP = $_SERVER['REMOTE_ADDR'];
// Vars we want to pass to the system
$aJSVars = array(
'member_url' => $es->getConfig('memberUrl'),
'base_url' => $es->getCOnfig('baseUrl'),
'image_url' => $es->getConfig('imageUrl'),
'date' => date("F d, Y H:i:s", time()),
);
$ba = new BannerAd();
?>
2nd
Fatal error: Class 'FOrum' not found in /home/musthand/public_html/interface/forum.php on line 33
<?php
global $es;
global $ui;
global $member_id;
global $base_url;
global $member_url;
global $image_url;
global $admin_url;
require_once("includes/EliteScript.php");
$es = new EliteScript();
$ui = new UserInterface();
$es->RequireMember();
$member_id = $es->GetMemberId();
$base_url = $es->GetConfig("baseUrl");
$member_url = $es->GetConfig("memberUrl");
$image_url = $es->GetConfig("imageUrl");
$es->DisplayHeader("Forum", "member.php");
$_REQUEST["do"];
display_main();
$es->DisplayFooter();
function display_main()
{
global $es;
global $ui;
global $member_id;
global $base_url;
global $member_url;
global $image_url;
global $admin_url;
$cur_sign = $es->GetCurrencySign();
$f = new FOrum();
echo "<script>\n</script>\n\n<div class=\"bigHeader\">Forum</div>\n";
echo $ui->GenerateMessageBox("msg", 0, 5);
echo $ui->GenerateErrorBox("err", 0, 5);
echo "\n";
echo $ui->DisplayToolTip("Forum", "Below you can participate in the company forum.");
echo "<br>\n\n\n";
$q = "SELECT * FROM forumSections ORDER BY id";
$r = mysql_query($q);
while( $l = mysql_fetch_array($r) )
{
$l_sid = $l["id"];
$l_sec_name = htmlentitiesi($l["name"]);
echo "<div class=\"header\">";
echo $l_sec_name;
echo "</div>\n<table cellspacing=\"1\" cellpadding=\"0\" border=\"0\" width=\"100%\" class=\"dataTbl\">\n<tr class=\"tblHeader\">\n<td>Forum</td>\n<td width=\"50\" align=\"center\">Topics</td>\n<td width=\"50\" align=\"center\">Replies</td>\n<td width=\"150\" align=\"right\">Last Post Info</td>\n</tr>\n";
$html = NULL;
$qb = "SELECT * FROM forums WHERE sectionId='" . $l_sid . "' ORDER BY id";
$rb = mysql_query($qb);
while( $lb = mysql_fetch_array($rb) )
{
$l_fid = $lb["id"];
$l_name = htmlentitiesi($lb["name"]);
$l_desc = htmlentitiesi($lb["description"]);
$l_topics = $f->GetForumTopicCount($l_fid);
$l_replies = $f->GetForumReplyCount($l_fid);
$html .= "<tr class=\"tblRowA\">\n\t\t\t<td style=\"padding: 5px 0px 5px 5px;\">\n\t\t\t<b>" . $l_name . "</b>\n\t\t\t<div style=\"padding-top: 5px;\">\n\t\t\t" . $l_desc . "\n\t\t\t</div>\n\t\t\t\n\t\t\t</td>\n\t\t\t<td align=\"center\">" . $l_topics . "</td>\n\t\t\t<td align=\"center\">" . $l_replies . "</td>\n\t\t\t<td align=\"right\">" . $l_lastpost . "</td>\n\t\t\t</tr>";
}
echo $html;
echo "</table>\n\n";
}
echo "\n\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n\n\n\n\n\n<div class=\"header\">News & Updates</div>\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n";
$html = NULL;
$q = "SELECT * FROM news ORDER BY added DESC,id DESC LIMIT 5";
$r = mysql_query($q);
while( $l = mysql_fetch_array($r) )
{
$l_id = $l["id"];
$l_title = htmlentitiesi($l["title"]);
$l_date = date("M jS", strtotime($l["added"]));
$html .= "<tr class=\"sepLine\"><td width=\"20\"><img src=\"" . $image_url . "/note.png\" width=\"16\" height=\"16\"></td><td>" . $l_title . " <i style=\"color:gray;\">(" . $l_date . ")</i></td></tr>\n";
}
if( !$html )
{
$html = "<tr class=\"sepLine\"><td style=\"color: gray;\">Currently no news and updates...</td></tr>";
}
echo $html;
echo "</table>\n<br>\n\n<div class=\"header\">Account Summary</div>\n\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n<tr class=\"sepLine\">\n<td width=\"20\"><img src=\"";
echo $image_url;
echo "/user.png\" width=\"16\" height=\"16\"></td>\n<td width=\"175\"><b>Member Info:</b></td>\n<td>";
echo $username;
echo " (#";
echo $member_id;
echo ") <i>(<a href=\"mailto:";
echo $email;
echo "\">";
echo $email;
echo "</a>)</i></td>\n<td align=\"right\"><a href=\"";
echo $member_url;
echo "/preferences.php\">[Preferences]</a></td>\n</tr>\n</table>\n\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n<tr><td class=\"toolTip\">\nYou must ";
echo $req_text;
echo " before participating.</td></tr>\n</table>\n\n\n\n\n<div class=\"header\">Current Active ";
echo $token_label;
echo "s</div>\n\n<table cellspacing=\"1\" cellpadding=\"0\" border=\"0\" width=\"100%\" class=\"dataTbl\">\n<tr class=\"tblHeader\">\n<td width=\"50\">ID</td>\n<td>Type</td>\n<td width=\"40\">Units</td>\n<td width=\"80\">Amount</td>\n<td width=\"150\">Earned So Far</td>\n<td width=\"80\">Created</td>\n</tr>\n\n";
$tok_types = $es->GetConfig("tokenTypes");
$html = NULL;
$tblClass = "tblRowA";
$q = "SELECT * FROM tokens WHERE memberId='" . $member_id . "' AND status = 'ACTIVE' ORDER BY created DESC,id DESC";
$r = mysql_query($q);
while( $l = mysql_fetch_array($r) )
{
$l_id = $l["id"];
$l_type = $l["type"];
$tok_arr = $tok_types[$l_type];
$l_name = htmlentitiesi($tok_arr["name"]);
$l_amt = $l["amount"];
$l_esf = $l["earnedSoFar"];
$l_exp_type = $l["expireType"];
$l_exp_val = $l["expiresOnValue"];
$l_created = $l["createdDate"];
$l_lastroi = $l["lastRoiDate"];
$l_incycle = $l["inCycle"];
$l_status = $l["status"];
if( $l_status == "ACTIVE" )
{
$lb_status = "<span style=\"color: darkgreen;\">Active</span>";
}
else
{
if( $l_status == "EXPIRED" )
{
$lb_status = "<span style=\"color: red;\">Expired</span> as of " . date("M jS, y", strtotime($l["expiresDate"]));
}
}
if( $l_created == $l_lastroi && $l_incycle <= 1 )
{
$l_lastearn_text = "Never";
}
else
{
$l_lastearn_text = date("M jS, y", strtotime($l_lastroi));
}
$l_units = sprintf("%d", $l["units"]);
$l_earned_per = sprintf("%.2f", $l_esf / $l_amt * 100);
$earned_per_style = "color: gray;";
if( 100 < $l_earned_per )
{
$earned_per_style = "color: darkgreen;";
}
$l_created_date = date("M jS, y", $l["created"]);
if( $l_exp_type == "value" )
{
$l_exp_text = sprintf("%.2f", $l_exp_val) . "%";
$l_exp_text .= " <i>(" . $cur_sign . sprintf("%.2f", $l_amt * $l_exp_val / 100) . ")</i>";
}
else
{
if( $l_exp_type == "date" )
{
$l_exp_text = date("M jS, y", $l["expires"]);
}
else
{
if( $l_exp_type == "never" )
{
$l_exp_text = "No Set Expiry";
}
}
}
$lb_amt = number_format($l_amt, 2);
$lb_esf = number_format($l_esf, 2);
$html .= "\n\t\t<tr class=\"" . $tblClass . "\">\n\t\t<td>#" . $l_id . "</td>\n\t\t<td><b>" . $l_name . "</b></td>\n\t\t\n\t\t<td>" . $l_units . "</td>\n\t\t<td>" . $cur_sign . $lb_amt . "</td>\n\t\t<td>" . $cur_sign . $lb_esf . " <i style=\"" . $earned_per_style . "\">(" . $l_earned_per . "%)</i></td>\n\t\t<td>" . $l_created_date . "</td>\n\t\t</tr>\n\t\t<tr class=\"" . $tblClass . "\">\n\t\t<td colspan=\"6\" style=\"padding-left: 20px;\">\n\t\t\n\t\t<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n\t\t<tr><td width=\"170\">\n\t\t<u>Last Earn Date:</u> " . $l_lastearn_text . "\n\t\t</td><td width=\"190\">\n\t\t<u>Expires:</u> " . $l_exp_text . "\n\t\t</td><td>\n\t\t<u>Status:</u> " . $lb_status . "\n\t\t</td></tr>\n\t\t</table>\n\t\t\n\t\t</td>\n\t\t</tr>";
$tblClass = $tblClass == "tblRowA" ? "tblRowB" : "tblRowA";
}
if( !$html )
{
$html .= "<tr class=\"" . $tblClass . "\"><td colspan=\"7\"><span style=\"color: gray;\">Currently no active " . $token_label . "s...</span></td></tr>";
}
echo $html;
echo "</table>\n\n<br><br>\n\n";
}
?>
They used to work fine on old server, I don't know what's up with these errors on new one.
They're defined somewhere in somefile, there are 800+ files and it's hard to search in each and every.
Is there any way that we can make the server look of the actual file where these classes or variables were defined?
Your code was never working well. It is bad written. The reason you did not see errors, in your old server is that you had lower error reporting or the whole error reporting was turned off. When you are developing something you should always develop with turned on error reporting, so you can see your mistakes.
The first problem is here
if(!is_object($es)) {
You check directly if $es is object, but this is wrong, because this statement is at the top of the file, and $es will be aways undefined unless you import it from the global scope, like this:
global $es;
if(!is_object($es)) {
Your second error is because you have referenced wrongly the Forum class:
$f = new FOrum();
I suppose it should be:
$f = new Forum();

facebook graph api video pulling

I'm trying to embed a facebook video gallery on a website.
My problem is that it only shows one video, while the facebook graph shows multiple. How can I make all the videos appear?
<?php
$json_link = "https://graph.facebook.com/sophia.deboer/videos?access_token=862683673820828|15Gx44NW43LHI92o__bRPA6lz44&fields=id,name,description,created_time,from,source&limit=10";
$json = file_get_contents($json_link);
$obj = json_decode($json, true);
$feed_item_count = count($obj['data']);
for ($x = 0; $x < 10; $x++) {
echo "<div class='item_box'>";
echo "<div style='overflow:hidden;'>";
// video source
$source = $obj['data'][$x]['source'];
echo "<div class='col-lg-6'>";
echo "<video src='{$source}' controls>";
echo "Your browser does not support the video tag.";
echo "</video>";
echo "</div>"; // end 'row'
echo "<div class='col-lg-6'>";
// user's custom message
$name = isset($obj['data'][$x]['name']) ? htmlspecialchars_decode($obj['data'][$x]['name']) : "Video #" . $obj['data'][$x]['id'];
$description = htmlspecialchars_decode(str_replace("\n", "<br>", $obj['data'][$x]['description']));
// when it was posted
$created_time = $obj['data'][$x]['created_time'];
$converted_date_time = date('Y-m-d H:i:s', strtotime($created_time));
$ago_value = time_elapsed_string($converted_date_time);
// from
$page_id = $obj['data'][$x]['from']['id'];
$page_name = $obj['data'][$x]['from']['name'];
echo "<h2 style='margin: 0 0 .5em 0;'>{$name}</h2>";
echo "<div>";
echo $description;
echo "</div>";
echo "<div style='margin:.5em 0 0 0; color: #999;'>";
echo "Posted {$ago_value} by <a href='https://facebook.com/{$page_id}' target='_blank'>{$page_name}</a>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "<hr />";
echo "</div>"; // end 'item_box'
}
?>
Demo
After removing :
$ago_value = time_elapsed_string($converted_date_time);
The code loops all videos.
I also changed this:
$feed_item_count = count($obj['data']);
for ($x = 0; $x < 10; $x++)
To This:
$feed_item_count = count($obj['data']);
for ($x = 0; $x < $feed_item_count; $x++)
<?php
$json_link = "https://graph.facebook.com/sophia.deboer/videos?access_token=862683673820828|15Gx44NW43LHI92o__bRPA6lz44&fields=id,name,description,created_time,from,source&limit=10";
$json = file_get_contents($json_link);
$obj = json_decode($json, true);
$feed_item_count = count($obj['data']);
for ($x = 0; $x < $feed_item_count; $x++) {
echo "<div class='item_box'>";
echo "<div style='overflow:hidden;'>";
// video source
$source = $obj['data'][$x]['source'];
echo "<div class='col-lg-6'>";
echo "<video src='{$source}' controls>";
echo "Your browser does not support the video tag.";
echo "</video>";
echo "</div>"; // end 'row'
echo "<div class='col-lg-6'>";
// user's custom message
$name = isset($obj['data'][$x]['name']) ? htmlspecialchars_decode($obj['data'][$x]['name']) : "Video #" . $obj['data'][$x]['id'];
$description = htmlspecialchars_decode(str_replace("\n", "<br>", $obj['data'][$x]['description']));
// when it was posted
$created_time = $obj['data'][$x]['created_time'];
$converted_date_time = date('Y-m-d H:i:s', strtotime($created_time));
//$ago_value = time_elapsed_string($converted_date_time);
// from
$page_id = $obj['data'][$x]['from']['id'];
$page_name = $obj['data'][$x]['from']['name'];
echo "<h2 style='margin: 0 0 .5em 0;'>{$name}</h2>";
echo "<div>";
echo $description;
echo "</div>";
echo "<div style='margin:.5em 0 0 0; color: #999;'>";
echo "Posted {$ago_value} by <a href='https://facebook.com/{$page_id}' target='_blank'>{$page_name}</a>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "<hr />";
echo "</div>"; // end 'item_box'
}
?>

Looping through every record from database

I've searched on the internet for this, and questions here on SO but mostly are using something else than PHP. So i will ask my own question.
What i need to do is make a button that will print out (read literally print, as in downloading a word document with all details on it) every record from the database.
The ID is named 'abstract_id'.
What i'm going to show you next is the print button from all pages, what i mean by this is if you click on said button it will print everything from that specific page:
$abstract_id = addslashes($_POST['abstract_id']);
//Here i connect to the database//
$query = "SELECT * FROM abstracts WHERE abstract_id = '$abstract_id'";
$result = mysql_query($query);
$i = 0;
$title = mysql_result($result,$i,"title");
$author[1] = mysql_result($result,$i,"author1");
$organization[1] = mysql_result($result,$i,"organization1");
$author[2] = mysql_result($result,$i,"author2");
$organization[2] = mysql_result($result,$i,"organization2");
$author[3] = mysql_result($result,$i,"author3");
$organization[3] = mysql_result($result,$i,"organization3");
$author[4] = mysql_result($result,$i,"author4");
$organization[4] = mysql_result($result,$i,"organization4");
$author[5] = mysql_result($result,$i,"author5");
$organization[5] = mysql_result($result,$i,"organization5");
$author[6] = mysql_result($result,$i,"author6");
$organization[6] = mysql_result($result,$i,"organization6");
$format = mysql_result($result,$i,"format");
$language = mysql_result($result,$i,"language");
$presenter = mysql_result($result,$i,"presenter");
$background = mysql_result($result,$i,"background");
$purpose = mysql_result($result,$i,"purpose");
$methods = mysql_result($result,$i,"methods");
$findings = mysql_result($result,$i,"findings");
$conclusion = mysql_result($result,$i,"conclusion");
$word_count = mysql_result($result,$i,"word_count");
$name = mysql_result($result,$i,"name");
$email1 = mysql_result($result,$i,"email1");
$email2 = mysql_result($result,$i,"email2");
$phone1 = mysql_result($result,$i,"phone1");
$phone2 = mysql_result($result,$i,"phone2");
$fax = mysql_result($result,$i,"fax");
$address = mysql_result($result,$i,"address");
$country = mysql_result($result,$i,"country");
$topic = mysql_result($result,$i,"topic");
$master_status = mysql_result($result, $i, "master_status");
$last_edit = mysql_result($result,$i,"last_edit");
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=abstract_" . $abstract_id . ".doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<p><b>PCNE Abstract</b> $abstract_id</p>";
echo "<h1>$title</h1>";
echo "<b>";
for ($i = 1; $i<= 6; $i++) {
echo ((!empty($author[$i-1]) && !empty($author[$i])) ? ", " : "") ;
echo ((!empty($author[$i])) ? $author[$i] . "<sup>" . $i . "</sup>" : "") ;
}
echo ".</b>";
echo "<br>";
for ($i = 1; $i<= 6; $i++) {
if (!empty($author[$i])) {
echo (!empty($organization[$i]) && !empty($organization[$i-1])) ? ". " : "";
echo ((!empty($organization[$i])) ? "<sup>" . $i . "</sup>" . $organization[$i]: "") ;
}
}
echo (!empty($email1)) ? " (" . $email1 . ")" : "";
echo "<br>";
echo "<br>";
echo "<b>Background</b> ";
echo "$background<br>";
echo "<b>Purpose</b> ";
echo "$purpose<br>";
echo "<b>Method</b> ";
echo "$methods<br>";
echo "<b>Findings</b> ";
echo "$findings<br>";
echo "<b>Conclusion</b> ";
echo "$conclusion<br>";
echo "</body>";
echo "</html>";
Now, this works fine, but i need a same working button which does almost the same, but instead of printing out 1 record it should print all. So all i basically need is a foreach or while loop that goes through every abstract_id.
It's been ages since i last programmed php, so i appreciate any help!
If you need any clarification, feel free to ask.
First you don't need your 30 lines of mysql_result, just use mysql_fetch_assoc to get all values in associative array.
Then you just have to do a while ( $line = mysql_fetch_assoc($query) ), see above :
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=abstract_all.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
$query = mysql_query("SELECT * FROM abstracts WHERE 1") or die(mysql_error()) ;
while ( $line = mysql_fetch_assoc($query) )
{
echo "<p><b>PCNE Abstract</b>".$line['abstract_id']."</p>";
echo "<h1>".$line['title']."</h1>";
$authors = Array() ;
for ($i = 1 ; $i <= 6 ; $i++ )
if ( isset($line['author'.$i]) && $line['author'.$i] != '' ) $authors[] = $line['author'.$i].' <sup>'.$i.'</sup>' ;
echo '<b>'.implode(', ',$authors).'</b>' ;
$organizations = Array() ;
for ($i = 1; $i<= 6; $i++)
{
if ( ! isset($line['author'.$i]) || $line['author'.$i] == '' ) continue ; // Check if there is an author, if no go to next loop
if ( isset($line['organization'.$i]) && $line['organization'.$i] != '' ) $organizations[] = ' <sup>'.$i.'</sup> '.$line['organization'.$i] ;
}
echo '<b>'.implode(', ',$organizations).'</b>' ;
echo "<b>Background</b> ";
echo $line['background']."<br>";
echo "<b>Purpose</b> ";
echo $line['purpose']."<br>";
// ...
}
echo "</body>";
echo "</html>";

Categories