I have a piece of code that retrieves data from the Facebook api. Basically what happens is I loop over all the posts in our own database. For each posts it will try to get all shares for that post from the Facebook api. The Facebook api retrieves an object with a next link for the next batch of shares for that posts and it will keep looping till it gets all shares and go on to the next post.
The code looks as follows (Note that this is not my actual code because it has way to many things going on that are not important or needed for my question):
// SELECT all posts from my database
$sql = "SELECT * FROM posts";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
try {
//this is our api call to get all share posts
$response = $fb-get($row['postId'] . "someApiEndPointForSharedPosts");
//start processing the response for the post
processFeed($response);
} catch (Exception $e) {
//There is no response or there is another error
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
}
function processFeed($shares){
//Go through all shares in the response and do some modification and storage etc
foreach($shares as $share){
//Do something with the share
}
//Facebook sdk method to get the next batch of shares for the post (if there are any left)
$nextFeed = fb->next($shares);
//If there are more shares run this function again with the new batch
if(isset($nextFeed)){
processFeed($nextFeed);
}
}
Now my question is. Will the code run in the following order:
Select all post
Do the api call for the first post (which returns an response)
Start process feed with the response for the first post
Check if there is a next feed for the first post
If there is run process feed agian till there is no next feed left for the first post
Start over by doing the api call for the second post and do the above process agian.
Related
I need to make an PHP application where anybody can define a page name and get the public information of that page, specifically the followers count.
For example, Google's Facebook page (https://www.facebook.com/Google/) has 28.318.253 likes and 33.390.596 followers. How can I, programatically, get those numbers?
I want my final code to look something like this:
$page = "google";
// Some code logic, API calls or anything else
$likes = $pageData->likes_count;
$followers = $pageData->followers_count;
echo $likes; // Should output "28318253"
echo $followers; // Should output "33390596"
I'm trying to send an array with its values from the first page to the second page. On the second page what I want to happen is that it the sent array values will be transferred to a new array. Here's my current progress:
Snippet code of Report_Status.php (First Page / Source, where the
array with values is initailized)
$message = array(
'title' => 'Report Approved!',
'body' => 'Thank you for reporting! We already approved/verified your report as a legit fire incident. Wait for the firefighters to arrive.'
);
while ($User_Row = mysqli_fetch_array($Retrieve_User, MYSQLI_ASSOC)){
$User_Token[] = $User_Row['User_Token'];
}
send_notification($User_Token, $message); //calling a function of the second page.
//I will replace the it from calling a function to redirecting to a specific web link
This first page retrieves a specific data (which is the user's token) from the database and stores it into an array ($User_Token[]). Initialization.
Snippet code of Push_User_Notification.php (Second page / Destination, where the array with its values will be received.
//Here: there should be the code for catching/receving the array
$Retrieve_Target_Tokens_Query = "SELECT * FROM User WHERE User_Token = $tokens";
$Retrieve_Target_Tokens = mysqli_query($Connection, $Retrieve_Target_Tokens_Query);
$tokens = array();
if(!$Retrieve_Target_Tokens){
echo "<script type = 'text/javascript'> alert('Server Error: Could retrieve tokens from database because of this error: ". mysqli_error($Connection)."') </script>";
}
if(mysqli_num_rows($Retrieve_Target_Tokens) > 0){
while($Token = mysqli_fetch_array($Retrieve_Target_Tokens)){
$tokens[] = $Token['User_Token'];
}
}
$message = array("message" => "Your Report has been approved by an admin! Please wait for firefighter/s to arrive.");
send_notification($tokens, $message);
function send_notification ($tokens, $message)
{
//Process of Firebase sending notification here (No problem on this function)
}
Question:
How can i send an array from a one page and receive it successfully to another page?
P.S. This code/s sends a push notification to specific android users only.
You can use Session variable the link : http://php.net/manual/en/reserved.variables.session.php
or you can pass it with JSON if you want to do it with a call in Javascript.
Hope it was helpful :)
I would use sessions for this.
Here's a similar question with the answer you need: Pass array from one page to another
I have a CodeIgniter PHP application that shows two movie covers. Beside them is a "random movie" button that uses AJAX to replace the two movies with a new set of movies. You can continue to click this, over and over, and see it continue to replace the images of the movie covers. The first two covers to show are set as the defaults, and they should never show after the user has clicked the random movie button. The problem is this: When clicking the random movie button, it will some times take many clicks to finally show a new cover. That is, the same cover will be returned multiple times in a row. The two different covers being fetched are being called from slightly different URLs, so they will rarely both break at the same time. This lets me know that it is refreshing, but that the function is returning the same movie multiple times. If I access the url that is being called via AJAX directly, I never see this take place since I have used the Session class to store the last movie's and exclude it from the SQL query (i.e. WHERE id NOT IN ($default_movie, $last_movie)). Any idea why accessing the url directly would work fine, but when calling via AJAX, I'm seeing this behavior?
I know this may not have been as clear as possible, so let me know if I can clarify something that doesn't make sense. I'll add code if that helps as well. Thanks friends!
Query to get random movie:
SELECT * FROM (`movies`) WHERE `id` NOT IN (2, 10) ORDER BY RAND() LIMIT 1
Model method:
public function getRandom($count = 1, $featured = FALSE, $series = FALSE, $exclude = 0, $last = 0) {
$this->db->order_by('id', 'random');
$this->db->limit(1);
$conditions = array();
if ($exclude > 0) {
$conditions['id !='] = $exclude;
}
if ($last > 0) {
if (!empty($conditions['id !='])) {
$conditionsNotIn = "id NOT IN (" . $conditions['id !=']. ", $last)";
unset($conditions['id !=']);
$this->db->where($conditionsNotIn);
} else {
$conditions['id !='] = $last;
}
}
if ($featured) {
$conditions['featured'] = 1;
}
if ($series) {
$conditions['current_series'] = 1;
}
$movie = $this->db->get_where('movies', $conditions);
$movie = $movie->row();
if (!is_null($movie)) {
return $movie;
} else {
return FALSE;
}
}
Any idea why accessing the url directly would work fine, but when
calling via AJAX, I'm seeing this behavior?
I have an idea yes.
Browser caching.. PITA!
Try turning off caching explicitly:
$.ajaxSetup({cache: false});
Put that before your ajax request, assuming you're using jQuery.
If you're not you need to append some random variable to the url, this keep the browser from caching the requests.
I've built a contest system where users submit tickets then one is randomly chosen to win, and now I'm trying to figure out a way to display to users the tickets they have already submitted. Each ticket has an id, a date, and an invoicenumber. I want to display all the invoice numbers that a user has submitted so far.
Here is the method I have in my methods page. (I've organized my methods into one php file and then i just call them when needed.)
function GetSubmittedBallots()
{
if(!$this->CheckLogin())
{
$this->HandleError("Not logged in!");
return false;
}
$user_rec = array();
if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
{
return false;
}
$qry = "SELECT invoicenumber FROM entries WHERE user_id = '".$user_rec['id_user']."'";
$result = mysql_query($qry,$this->connection);
while($row = mysql_fetch_array($result))
{
echo $row['invoicenumber'];
}
}
and then on my html page that I want it to echo on, i just call it
<?php GetSubmittedBallots(); ?>
Sadly, this doesn't work. So my question is, how would i go about displaying the $row array on my html page?
<?php
require("methods.php"); // Include the file which has the "GetSubmittedBallots" function or method, if it's in a separate file
GetSubmittedBallots(); // Run the function / method
?>
If this doesn't work, please let us know any errors you receive.
Does it echo "Array"?
That's because you are trying to echo an array.
You should use something like print_r or var_dump, given that you are just trying to access the queried results. In my opinion the method should build a multidimensional array with the records, and then the template logic should loop through them and echo the values in a nice way. Be it a table or nicely arranged HTML.
If I'm not wrong, $this keyword is indicating you're in a class? If so, you need first to init that class and try to call GetSubmittedBallots function after init;
// assuming that class's name is Users
$users = new Users();
$users->GetSubmittedBallots();
i have page on Facebook and I want to display latest 5 posts from my feed/wall on a page to my website. How to do this? I found this solution.. it is easy
https://developers.facebook.com/docs/reference/plugins/like-box/
and someone guide me to use facebook api and do it myself
what is the best way?
I use php mysql to build this site
Here is the PHP code. You need to place this in your template.
<ul>
<?php
//function to retrieve posts from facebook’s server
function loadFB($fbID){
$url = "http://graph.facebook.com/".$fbID."/feed?limit=3";
// Update by MC Vooges 11jun 2014: Access token is now required:
$url.= '&access_token=YOUR_TOKEN|YOUR_ACCESS_SECRET';// *
//load and setup CURL
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
//get data from facebook and decode JSON
$page = json_decode(curl_exec($c));
//close the connection
curl_close($c);
//return the data as an object
return $page->data;
}
/* Change These Values */
// Your Facebook ID
$fbid = "190506416472588";
// How many posts to show?
$fbLimit = 10;
// Your Timezone
date_default_timezone_set("America/Chicago");
/* Dont Change */
// Variable used to count how many we’ve loaded
$fbCount = 0;
// Call the function and get the posts from facebook
$myPosts = loadFB($fbid);
//loop through all the posts we got from facebook
foreach($myPosts as $dPost){
//only show posts that are posted by the page admin
if($dPost->from->id==$fbid){
//get the post date / time and convert to unix time
$dTime = strtotime($dPost->created_time);
//format the date / time into something human readable
//if you want it formatted differently look up the php date function
$myTime=date("M d Y h:ia",$dTime);
?>
<ul>
<li><?php echo($dPost->message) . $myTime; ?></li>
</ul>
<?php
//increment counter
$fbCount++;
//if we’ve outputted the number set above in fblimit we’re done
if($fbCount >= $fbLimit) break;
}
}
?>
</ul>
Two things you must do for working out this script.
Make sure your server is cURL enabled
You will have change the Facebook ID in the script by yours.
* You can get the access token this way:
$token = 'https://graph.facebook.com/oauth/access_token?client_id='.APP_ID.'&client_secret='.APP_SECRET.'&grant_type=client_credentials';
$token = file_get_contents($token); // returns 'accesstoken=APP_TOKEN|APP_SECRET'
Login to facebook
Go to facebok developers section "Apps"
Register new app, you need only to register new app, all additional data is optional
Copy your App ID/API Key and App Secret from that same "Apps" section.
Copy facebook.php and base_facebook.php files from repo to your server
Use polymorphic query to api, to request wall content from facebook account
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
$fbApiGetPosts = $facebook->api('/YOUR_FACEBOOK_ACCOUNT_ID/feed?limit=5');
if (isset($fbApiGetPosts["data"]) && !empty($fbApiGetPosts["data"])) {
// display contents of $fbApiGetPosts["data"] array
}
Replace YOUR_APP_ID with your app ID, YOUR_APP_SECRET with your app secret and YOUR_FACEBOOK_ACCOUNT_ID with target facebook account, you want to get posts from.
Polymorphic query basically is path/URL. More info inside previously mentioned facebook api reference docs.
If your target facebook account wall is public, you won't need anything else that this, to view them.
I had trouble with Okky's answer here, and I found a possible, albeit not an ideal workaround.
Use an RSS feed of your Facebook wall, then simply parse it with an RSS reader of your choosing.
https://www.facebook.com/feeds/page.php?format=rss20&id=YOUR_UNIQUE_ID
Here is a quick way to get your ID
So to mix up Okky and Deele answer, that both help me out, you must end with something that will look like this. I also add an anchor tag to link to the post url :
<?php
$fbApiGetPosts = $facebook->api('/YOUR_FACEBOOK_ACCOUNT_ID/feed?limit=5');
if (isset($fbApiGetPosts["data"]) && !empty($fbApiGetPosts["data"])) {
//loop through all the posts we got from facebook
foreach($fbApiGetPosts["data"] as $dPost){
//only show posts that are posted by the page admin
if($dPost["from"]["id"]==$fbid){
//get the post date / time and convert to unix time
$dTime = strtotime($dPost["created_time"]);
//format the date / time into something human readable
//if you want it formatted differently look up the php date function
$myTime=date("M d Y h:ia",$dTime);
?>
<li><a href="<?php echo($dPost["link"]); ?>">
<?php echo($dPost["message"]) . "<br>" .
$myTime; ?></a></li>
<?php
}
}
}
?>