How to get Facebook Page Feed with graph API using PHP & MySQL
Tips & Tricks 22-Oct-2016

How to get Facebook Page Feed with graph API using PHP & MySQL

Let’s start from app creation.

Step 1: create Facebook application click here

step 1 Facebook for Developers

Step 2: Chose platform where to use application select website.

Step 2 Facebook for Developers

Step 3: Write your application name and click Create New Facebook App ID button.

step 3 Facebook for Developers

Step 4: Select settings for application and give your email.

step 4 Facebook for Developers

Step 5: Skip quick start

step 5 Facebook for Developers

Step 6: App setup from sandbox to live on review page

step 6 App Review Facebook for Developers

Final Step for application creation and setting: Copy application ID and Secret from settings page

step 7 phpgang feed app Dashboard Facebook for Developers

Now Coding for your feed application

Feed_database.sql

Import tables in your database.

-- phpMyAdmin SQL Dump
-- version 2.8.0.1
-- http://www.phpmyadmin.net
-- 
-- Host: custsql-pow22
-- Generation Time: May 16, 2016 at 05:16 AM
-- Server version: 5.5.46
-- PHP Version: 4.4.9
-- 
-- Database: `database`
-- 

-- --------------------------------------------------------

-- 
-- Table structure for table `feed`
-- 

CREATE TABLE `feed` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `PageID` varchar(100) NOT NULL,
  `Date` datetime NOT NULL,
  `Post` text NOT NULL,
  `Picture` text NOT NULL,
  `Comments` varchar(10) NOT NULL,
  `Likes` varchar(10) NOT NULL,
  `Shares` varchar(10) NOT NULL,
  `PostID` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `PostID` (`PostID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- 
-- Dumping data for table `feed`
-- 


-- --------------------------------------------------------

-- 
-- Table structure for table `pages`
-- 

CREATE TABLE `pages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `PageID` varchar(100) NOT NULL,
  `Name` varchar(255) NOT NULL,
  `Likes` varchar(100) NOT NULL,
  `Talking` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- 
-- Dumping data for table `pages`
--

db.php

Configure your database connection file.

<?php

$connection = mysqli_connect('localhost','DBUser','DBPassword','DBName') or die(mysqli_error($connection));
?>

config.php

Application configuration file, modify CALL BACK URLYour App ID and Your App Secret values.

<?php

//Facebook configuration
$config['App_ID']      =   'YOUR_FACEBOOK_APPLICATION_ID';
$config['App_Secret']  =   'YOUR_FACEBOOK_APPLICATION_SECRET'; 

?>

index.php

Index file used to show you a form where you need to add your application unique name or id.

Page Name or page id

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Facebook Pages Feed</title>
</head>
<body>
<form method='post' action='feed.php'>Enter Page unique id / unique name here: <input type='text' name='page' value="" /><input type=submit /></form>
</body>
</html>

feed.php

This is the main file used to get page info and feeds and store in database.

<?php
if(isset($_REQUEST['page']))
{
 require_once('db.php'); // Database connection
 require_once( 'config.php' ); // Configuration file contain facebook application id and secret
 $token = $config['App_ID']."|".$config['App_Secret']; // making app token by its id and secret
 
 $pageDetails = getFacebookId(mysqli_real_escape_string($connection,$_REQUEST['page'])); // Get page details like name of page, page ID, Likes, people talking about that page.
 if(!isset($pageDetails->id))
 {
 echo "Error Occured please provide a valid facebook page unique id / unique name";
 exit;
 }
 $query = "SELECT * FROM pages where PageID='".$pageDetails->id."'"; // select page already in database or not query.
 $result = mysqli_query($connection,$query); // execute query
 $numResults = mysqli_num_rows($result); // number of records
 if($numResults>=1) // if page found in database then run update query
 {
 $Results = mysqli_fetch_array($result);
 mysqli_query($connection,"UPDATE `pages` SET `Name` = '".mysqli_real_escape_string($connection,$pageDetails->name)."',`Likes` = '".$pageDetails->fan_count."',`Talking` = '".$pageDetails->talking_about_count."' 
 WHERE `id` ='".$Results['id']."' LIMIT 1");
 }
 else // else run insert query for new page
 {
 mysqli_query($connection,"INSERT INTO `pages` ( `id` , `PageID` , `Name` , `Likes` , `Talking` )
 VALUES 
 (NULL , '".$pageDetails->id."', '".$pageDetails->name."', '".$pageDetails->fan_count."', '".$pageDetails->talking_about_count."')");
 }

 feedExtract("",$pageDetails->id,$token); // This function will get feed of page.
 header("Location: view.php");
 exit;
}
else
{
 header("Location: index.php");
 exit;
}
 
// Function to get all feed of a page with like, comment and share count.
function feedExtract($url="",$pageFBID) // $url contain url for next pages and $page contain page id
{
 global $token, $connection; // database connection and tocken required
 
 // first time fetch page posts
 $response = file_get_contents_curl("https://graph.facebook.com/v2.6/$pageFBID/feed?fields=picture,message,story,created_time,shares,likes.limit(1).summary(true),comments.limit(1).summary(true)&access_token=".$token);
 
 $query = "SELECT id FROM pages where pageID='".$pageFBID."'"; // select feed already in database or not query.
 $result = mysqli_query($connection,$query); // execute query
 $fieldID = mysqli_fetch_row($result);
 $pageID = $fieldID['0'];
 // decode json data to array
 $get_data = json_decode($response,true);
 // loop extract data
 for($ic=0;$ic<count($get_data['data']);$ic++)
 {
 // Exracting Day, Month, Year
 $date = date_create($get_data['data'][$ic]['created_time']);
 $newDate = date_format($date,'Y-m-d H:i:s');
 
 
 // $story of post in if link, video or image it will return "message" plain status as "story"
 $story = $get_data['data'][$ic]['message'];
 
 if(!isset($story))
 $story = $get_data['data'][$ic]['story'];
 
 
 $query = "SELECT id FROM feed where PostID='".$get_data['data'][$ic]['id']."'"; // select page id from pages table.
 $result = mysqli_query($connection,$query); // execute query
 $numResults = mysqli_num_rows($result); // number of records
 if($numResults>=1) // if post found in database then run update query
 {
 //Update Record
 mysqli_query($connection,"update `feed` set 
 `Comments` = '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['comments']['summary']['total_count'])."' , 
 `Likes` = '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['likes']['summary']['total_count'])."', 
 `Shares` = '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['shares']['count'])."' 
 where `PostID` = '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['id'])."'");
 }
 else
 {
 
 // Puting data in sql query values
 $dataFeed = "(
 '".mysqli_real_escape_string($connection,$pageID)."', 
 '".mysqli_real_escape_string($connection,$newDate)."',
 '".mysqli_real_escape_string($connection,$story)."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['picture'])."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['comments']['summary']['total_count'])."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['likes']['summary']['total_count'])."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['shares']['count'])."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['id'])."')";
 
 mysqli_query($connection,"INSERT INTO `feed` (`PageID` , `Date` , `Post` , `Picture` , `Comments` , `Likes` , `Shares` , `PostID` ) VALUES $dataFeed");
 }
 }
 
 // Return message.
 return 1;
}

function getFacebookId($pageID) // This function return facebook page details by its url
{
 // get token from main file
 global $token; 
 $json = file_get_contents_curl('https://graph.facebook.com/'.$pageID.'?fields=fan_count,talking_about_count,name&access_token='.$token); 
 // decode returned json data in arrau.
 $json = json_decode($json);
 return $json;
}

?>

This file will get latest 25 posts of your given page and store in database and display them on view.php file attached in download source code.