Posts

Home jQuery

Convert a DIV Area to an Editable HTML Form

Hello guys! today we are going to do a code that converts a DIV area to an editable HTML form and save the changes to the database.

We are going to use jQuery, PHP & MySQL ofcourse.

My inspiration for this post is Youtube!

For beginners, this post covers some useful stuff like:

  • jQuery on(), post(), hover(), text(), val(), serialize(), css(), show() and hide() function examples
  • For PDO, we'll cover how to use the SELECT and UPDATE commands for database interaction.
  • You will also learn or see an example on how to submit form without page refresh (AJAX).

Our database would look like this:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `gender` varchar(6) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=56 ;
–
– Dumping data for table `users`
–

INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `username`, `password`, `modified`) VALUES
(28, 'John', 'Dalisay', 'Male', 'john', 'john123′, '2012-07-23 13:26:39′);

The Code

our libs/db_connect.php code, change as you needed.

<?php
$host = "localhost";
$db_name = "codeofaninja";
$username = "root";
$password = "";
try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

our index.php code:

<html>
    <head>
        <title>Div to Form – https://codeofaninja.com/</title>
        <!–just to include some styles –>
        <link rel="stylesheet" type="text/css" href="css/style.css" />
    </head>
<body>
<div id='banner'>
    <h2>Code of a Ninja Programming Blog</h2>
    <div>Converting a div to an editable HTML form and save changes to database</div>
</div>

<?php
//just getting the id of the user to be edited
$id = $_REQUEST['id'];

//connect to database
include 'libs/db_connect.php';

try {

    //prepare query
    $query = "select id, firstname, lastname, gender from users where id = ? limit 0,1″;
    $stmt = $con->prepare( $query );
    
    //this is the first question mark on the query above
    $stmt->bindParam(1, $id);
    
    //execute our query
    $stmt->execute();
    
    //store retrieved row to $row variable
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    //values to fill up our form
    $firstname = $row['firstname'];
    $lastname = $row['lastname'];
    $gender = $row['gender'];
    
}catch(PDOException $exception){ //to handle error
    echo "Error: " . $exception->getMessage();
}

?>
<!–start of our form –>
<form id='user_form'>

<!–id field is hidden, this is used to identify what row is to be edited–>
<input type='hidden' value='<?php echo $id; ?>' name='id'/>

<!–
    -just a form made with divs
    -when this div was clicked, it will be a form
–>
<div id='form_div'>
    
    <div class='field'>
        <div class='field_lbl'>Firstname:</div> <!–field name divs –>
        <div class='field_val'>
            <div class='field_div'>
                <!–
                    -this shown on page load
                    -and is hidden when the form_div was clicked
                    -and will be shown again when the user clicked anywhere outside the form_div or cancel button
                –>
                <div id='firstname_text'><?php echo $firstname; ?></div>
            </div>
            <div class='field_input'>
                <!–
                    -this is hidden on page load
                    -and is shown when form_div was clicked
                    -and will be hidden again when the user clicked anywhere outside the form_div or cancel button
                –>
                <input type='text' value='<?php echo $firstname; ?>' name='firstname' id='firstname'/>
            </div>
            <div class='clear_fix'></div>
        </div>
        <div class='clear_fix'></div>
    </div>
    <div class='clear_fix'></div>
    
    <!–same explanation above are given to these next fields–>
    <div class='field'>
        <div class='field_lbl'>Lastname:</div>
        <div class='field_val'>
            <div class='field_div'>
                <div id='lastname_text'><?php echo $lastname; ?></div>
            </div>
            <div class='field_input'><input type='text' value='<?php echo $lastname; ?>' name='lastname' id='lastname' /></div>
            <div class='clear_fix'></div>
        </div>
        <div class='clear_fix'></div>
    </div>
    <div class='clear_fix'></div>
    
    <div class='field'>
        <div class='field_lbl'>Gender:</div>
        <div class='field_val'>
            <div class='field_div'>
                <div id='gender_text'><?php echo $gender; ?></div>
            </div>
            <div class='field_input'>
                <select name='gender' id='gender'>
                    <option <?php if($gender == "Male") echo "selected";  ?> >Male</option>
                    <option <?php if($gender == "Female") echo "selected";  ?>>Female</option>
                </select>
            </div>
            <div class='clear_fix'></div>
        </div>
        <div class='clear_fix'></div>
    </div>
    <div class='clear_fix'></div>
    
    <!–
    -these buttons are hidden on page load
    -they are shown when form_div was clicked
    -and will be hidden again when the user clicked anywhere outside the form_div or cancel button
    —>
    <div class='btns'>
        <input type='button' value='Save' id='save_btn' />
        <input type='button' value='Cancel' id='cancel_btn' />
    </div>
    
</div>

</form>

<script src="js/jquery.min.js "></script>
<script type='text/javascript'>
$( document ).ready( function(){

    enable_hover(); //hover effect is enabled on page load

    $('#form_div').click(function(){
        edit_mode();
    });
    
    //when clicked the cancel button
    $('body').on('click', '#cancel_btn', function(){
        normal_mode(); //back to normal mode
    });
    
    //we used the jquery delegate func for live events
    $('body').on('click', '#save_btn', function(){
        
        //save first here
        //get the current values
        var fn = $('#firstname').val();
        var ln = $('#lastname').val();
        var gender = $('#gender').val();
        
        //the make it appear in the UI
        $('#firstname_text').text(fn);
        $('#lastname_text').text(ln);
        $('#gender_text').text(gender);
        
        //save the actual data
        //we use jquery serialize to serialize the form and easily get the form values
        //this is how to submit or post form without page refresh
        $.post("save.php", 
            $("#user_form").serialize(),
            function(data) {
                //you can do any event you want here
                alert(data); //alert that the date were saved
                normal_mode(); //back to normal mode
            });
            
    });
    
    //this way we can detect if the user clicked outside the form_div area
    $("body").click(function(e) {
        if (e.target.id == "form_div" || $(e.target).parents("#form_div").size()) { 
            //if clicked inside form_div area,
            //do nothing
        } else {
            //if the user clicked outside the form_div area, 
            //we'll be in normal mode
            normal_mode();
        }
    });
   

    
});

function edit_mode(){

    $('#form_div').css({ 'background-color' : '#fff' }); //just make a white background
    $('#form_div').unbind('hover'); //disable hover
    
    $('.field_div').hide(); //hide the text
    $('.field_input').show(); //show the form element
    $('.btns').show(); //show the buttons

}

//the normal state is the appearance of the page/element when it was first loaded
function normal_mode(){
    enable_hover(); //enable the hover effect again
    $('.field_div').show(); //show the texts
    $('.field_input').hide(); //hide the input elements
    $('.btns').hide(); //hide the buttons
}

//hover effect is used when NOT in 'edit form' mode
//we unbind this effect when we are in the 'edit form' mode
function enable_hover(){
    $('#form_div').hover(
        function(){ //when we hover form_div, bg will be gray with a bit of rounded corners
            $(this).css({
                    'background-color' : '#dcdcdc',
                    '-moz-border-radius' : '5px',
                    'border-radius' : '5px'
                    });
        },
        function(){ //when mouse is not hovered, bg will be transparent
            $(this).css({'background-color' : 'transparent'});
        }
    );
}
</script>

</body>
</html>

our save.php code:

<?php
//this is where the data were updated/saved
//connect to database
include 'libs/db_connect.php';

try{
    
    //write query
    //in this case, it seemed like we have so many fields to pass and 
    //its kinda better if we'll label them and not use question marks
    //like what we used here
    $query = "update 
                users 
            set 
                firstname = :firstname, 
                lastname = :lastname,
                gender = :gender
            where id = :id";

    //prepare query for excecution
    $stmt = $con->prepare($query);

    //bind the parameters
    $stmt->bindParam(':firstname', $_POST['firstname']);
    $stmt->bindParam(':lastname', $_POST['lastname']);
    $stmt->bindParam(':gender', $_POST['gender']);
    $stmt->bindParam(':id', $_POST['id']);
    
    // Execute the query
    if( $stmt->execute() ){
        echo "Record was updated.";
    
    }else{
        echo "Unable to update record.";
    }

}catch(PDOException $exception){ //to handle error
    echo "Error: " . $exception->getMessage();
}
?>

our style.css file:

body{
    margin:0;
    font-family:arial, verdana, tahoma;
}
#banner{
    margin:0 0 50px 0;
    padding:20px;
    width:100%;
    height:100px;
}

#form_div{
    padding:10px;
    width:500px;
    margin:0 auto;
}

.field{
    padding: 10px;
}

.field_lbl{
    float:left;
    margin:0 10px 0 0;
    width:80px;
    font-weight:bold;
}

.field_val{
    float:left;
}

.field_div{
    display:block;
}

.field_input{
    display:none;
}

.btns{
    display:none;
    margin:0 0 0 8px;
}

.clear_fix{
    clear:both;
}

Thank you guys for your kind comments, messages and suggestions. I really appreciate it!

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Thank you for learning from our post about Convert a DIV Area to an Editable HTML Form.

Home PHP

How To Create Dynamic Pie Chart in PHP or JavaScript with MySQL?

Graphical or visual representation of data is usually a requirement for a software, mostly, business apps. Today I'm going to show you the two and free ways to generate dynamic Pie Charts for your web applications.

We say "dynamic" because the data that will be shown in the pie chart were pulled from a database which can be updated frequently.

You can also create other types of charts such as bar charts, line charts, and many other types of charts, but in this post, we will cover pie charts only which can give you a good idea on how to create dynamic charts.

how to create dynamic pie chart in php or javascript

In this post, we will cover the following topics:

1.0 Dummy Database for Dynamic Pie Chart
2.0 Using LibChart to Create Dynamic Charts (PHP)
3.0 Using the Google Chart Tools (JavaScript)

The first way I will give you is generating a chart using PHP, and in the second way, we will use JavaScript.

1.0 Dummy Database for Dynamic Pie Chart

This will be our example table and data.

--
-- Table structure for table `programming_languages`
--

CREATE TABLE IF NOT EXISTS `programming_languages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `ratings` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

--
-- Dumping data for table `programming_languages`
--

INSERT INTO `programming_languages` (`id`, `name`, `ratings`) VALUES
(1, 'C', 17),
(2, 'Java', 16),
(3, 'C++', 9),
(4, 'Objective-C', 9),
(5, 'C#', 7),
(6, 'Basic', 6),
(7, 'PHP', 5),
(8, 'Phyton', 3),
(9, 'Pearl', 2),
(10, 'Ruby', 1);

2.0 Using LibChart to Create Dynamic Charts (PHP)

We will do the first way using the LibChart, the simple and free PHP chart drawing library.

Here's a code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Pie Chart Demo (LibChart)- https://codeofaninja.com/</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" />
</head>
<body>

<?php
    //include the library
    include "libchart/libchart/classes/libchart.php";

    //new pie chart instance
    $chart = new PieChart( 500, 300 );

    //data set instance
    $dataSet = new XYDataSet();
   
    //actual data
    //get data from the database
   
    //include database connection
    include 'db_connect.php';

    //query all records from the database
    $query = "select * from programming_languages";

    //execute the query
    $result = $mysqli->query( $query );

    //get number of rows returned
    $num_results = $result->num_rows;

    if( $num_results > 0){
   
        while( $row = $result->fetch_assoc() ){
            extract($row);
            $dataSet->addPoint(new Point("{$name} {$ratings})", $ratings));
        }
   
        //finalize dataset
        $chart->setDataSet($dataSet);

        //set chart title
        $chart->setTitle("Tiobe Top Programming Languages for June 2012");
       
        //render as an image and store under "generated" folder
        $chart->render("generated/1.png");
   
        //pull the generated chart where it was stored
        echo "<img alt='Pie chart'  src='generated/1.png' style='border: 1px solid gray;'/>";
   
    }else{
        echo "No programming languages found in the database.";
    }
?>

</body>
</html>

Some advantage of using the LibChart includes: Free, it will work even offline or if you're just debugging on your localhost, easy to use and can be used for multiple data sets.

Some disadvantages are: It is limited to Line, Bar and Pie charts only and it works with PHP5 only.

3.0 Using the Google Chart Tools (JavaScript)

Google chart tools are powerful, simple to use, and also free.

Our index.php code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Pie Chart Demo (Google VAPI) - https://codeofaninja.com/</title>
    </head>
   
<body style="font-family: Arial;border: 0 none;">
    <!-- where the chart will be rendered -->
    <div id="visualization" style="width: 600px; height: 400px;"></div>

    <?php

    //include database connection
    include 'db_connect.php';

    //query all records from the database
    $query = "select * from programming_languages";

    //execute the query
    $result = $mysqli->query( $query );

    //get number of rows returned
    $num_results = $result->num_rows;

    if( $num_results > 0){

    ?>
        <!-- load api -->
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
       
        <script type="text/javascript">
            //load package
            google.load('visualization', '1', {packages: ['corechart']});
        </script>

        <script type="text/javascript">
            function drawVisualization() {
                // Create and populate the data table.
                var data = google.visualization.arrayToDataTable([
                    ['PL', 'Ratings'],
                    <?php
                    while( $row = $result->fetch_assoc() ){
                        extract($row);
                        echo "['{$name}', {$ratings}],";
                    }
                    ?>
                ]);

                // Create and draw the visualization.
                new google.visualization.PieChart(document.getElementById('visualization')).
                draw(data, {title:"Tiobe Top Programming Languages for June 2012"});
            }

            google.setOnLoadCallback(drawVisualization);
        </script>
    <?php

    }else{
        echo "No programming languages found in the database.";
    }
    ?>
   
</body>
</html>

The advantages of using Google chart tools include: Free, easy to use, multiple data sets, and has wide range of charts types that you can use, looks good and interactive.

I think the only disadvantage will be: you cannot use it when you don't have internet connection.

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

How about you, do you have any other suggestions or solutions on how to create dynamic pie chart in PHP or JavaScript? Thanks for sharing it in the comments section below!

Home Facebook

Display Facebook Feed on Website Using PullFB Class

Update: Hi guys! I'm working on a new version of this code. Here's a sample LIVE DEMO. Let me know what you think! I'm going to post a new code and tutorial soon!

Hello guys! Today we are going to pull your Facebook page recent updates and display it to your website or to a webpage. This feature looks like a twitter widget (example is “My Twitter Updates” on the right sidebar of this site), but the posts were pulled from your Facebook page. This is good if you don’t want to use this Facebook Like Box social plugin and just want to show your page updates.

I updated the PullFB class a bit, to do this requirement. As I remember, this is one of the most requested feature, haha!
Our page_feeds.php code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja – Pull Feeds From Facebook</title>
        <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />

    </head>
<body>

<div style=’font-size: 16px; font-weight: bold; margin: 0 0 10px 0;’>
    This demo is synchronized with this
    <a href=’https://www.facebook.com/CodeOfANinja’ target=’_blank’>
        Code of a Ninja Official Facebook Page Feed
    </a>
</div>

<?php
//change as you needed
date_default_timezone_set(‘Asia/Manila’);

echo “<p>Recent Updates from The Code of a Ninja</p>”;

//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//include our class
include ‘pull_fb.class.php’;

//pass appId, appSecret, and page number (anyway, we’re not using paging here)
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//pass your fan page id
$feeds_result = $pull_fb->getFeeds( ’107786425949934′ );

//echo “<div>{$feeds_result->entries}</div>”;

foreach( $feeds_result->entries as $entries ){
    //just some time manipulation to suit my needs
    $ts = strtotime( “{$entries->published} +60 minutes” );

    echo “<div class=’object_item’ style=’text-align:left;’>”;
        //just for the sake of styling
        echo str_replace( “<br/><br/>”, “<br/>”, $entries->content );
        echo “<div class=’published_details’>”;
            echo “Published on “ . date( ‘m-d-Y H:i:s’, $ts );
            echo ” | <a href=’” . $entries->alternate . “‘ target=’_blank’>FB Link</a>”;
        echo “</div>”;
    echo “</div>”;

}
?>

  </body>
</html>

You can just copy and paste our updated PullFb class if you want. The code looks like this now:

<?php
require ‘fb-sdk/src/facebook.php’;

class PullFb{

    //set properties
    public $facebook;
    public $page_num;

    //number of items you want to see per page
    //you can add for other objects such as videos, etc.
    public $albums_per_page = 2;
    public $photos_per_page = 4;

    //if you want to exclude some albums like the Profile Pictures and Wall Photos, do something like:
    //$excluded_albums = “AND name <> ‘Profile Pictures’ AND name <> ‘Wall Photos’”;
    //in my example, I’m gonna exclude the wall photos only
    public $excluded_albums = “AND name <> ‘Wall Photos’”;

    //same with excluding photos, just state the pid
    public $excluded_photos = “AND pid <> ’221167777906963_1513599′ AND pid <> ’221167777906963_1513596′”;

    public function __construct( $appId, $secret, $page_num ){

        //create facebook instance
        $this->facebook = new Facebook(array(
          ‘appId’  => $appId,
          ‘secret’ => $secret,
          ‘cookie’ => true, // enable optional cookie support
        ));

        //for the page number
        $this->page_num = $page_num;
    }

    //get feeds in json format and then decode it using json_decode function
    public function getFeeds( $id ){
        $url = “https://www.facebook.com/feeds/page.php?id={$id}&format=json”;
        $feeds = json_decode( file_get_contents( $url ) );
        return $feeds;
    }

    //this will get facebook albums based on the $owner or fan page id
    public function getAlbums( $owner ){

        //we have to get the total number of albums first
        //i don’t know why the count function is not working
        $fql = “SELECT aid FROM album WHERE owner = {$owner} {$this->excluded_albums}“;

        //calculatePaging() will give us the paging settings
        //pass the fql and type of object
        $settings = $this->calculatePaging( $fql, ‘album’ );

        //get start and end limit for the next fql query
        $start_limit = $settings['start_limit'];
        $end_limit = $settings['end_limit'];

        //in this query we will include the paging based on the page number
        $fql = “SELECT
                    aid, object_id, owner, cover_pid, cover_object_id, name, created, modified,
                    description, location, size, link, visible, modified_major, edit_link,
                    type, can_upload, photo_count, video_count,
                    like_info, comment_info
                FROM
                    album
                WHERE
                    owner = {$owner} {$this->excluded_albums}
                LIMIT
                    {$start_limit}, {$end_limit}“;

        //set params
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset
        $result = $this->facebook->api( $params );

        //we will include the settings to our result variable
        $result['pull_fb'] = $settings;

        return $result;
    }

    //this function was made for paging
    public function calculatePaging( $fql, $type ){

        //set the params based on passed fql
        //to count the total number of records
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset
        $result = $this->facebook->api( $params );

        //get the total number of items
        $number_of_items = count( $result );

        //we will have the following calculations for the pagination
        //we just need some simple math

        //decide how many albums to show per page
        //values was actually declared as class property
        //you can easily add for other types of object
        if( $type == ‘album’ ){
            $items_per_page = $this->albums_per_page;
        }else if( $type == ‘photo’ ){
            $items_per_page = $this->photos_per_page;
        }

        //this is the current page
        $curr_page = $this->page_num;

        //previous page will be the current page MINUS one
        $prev_page = $curr_page - 1;

        //next page will be the current page PLUS one
        $next_page = $curr_page + 1;

        //no need to calculate for the first page, obviously, it’s 1
        //calculate last page
        $last_page = round( $number_of_items / $items_per_page );

        //detect if prev button will be visible
        if( $curr_page != 1 ){
            $prev_button = true;
        }

        //get $albums_shown value
        //it is the number of photos from the first page up to the current page
        $items_shown = $items_per_page * $curr_page;

        //detect if next button will be visible
        //if the $number_of_albums were still higher than the $albums_shown, show the next page button,
        //but if they are equal, don’t show the next page button
        if( $number_of_items > $items_shown ){
            $next_button = true;
        }

        //get start limit for the fql query
        $start_limit = $items_per_page * $prev_page;

        //get end limit
        //i’m not sure why i had to + 1, maybe it’s a facebook bug?
        $end_limit = $items_per_page + 1;

        //these are the values or settings returned
        //i made it to an array
        $settings = array(
            ‘number_of_items’ => $number_of_items,
            ‘prev_page’ => $prev_page,
            ‘next_page’ => $next_page,
            ‘prev_button’ => $prev_button,
            ‘next_button’ => $next_button,
            ‘start_limit’ => $start_limit,
            ‘end_limit’ => $end_limit,
            ‘last_page’ => $last_page
        );

        return $settings;
    }

    //to get photos of an album, we have to pass the album id
    public function getPhotos( $album_id ){

        //we have to get total number of photos first
        //i don’t know why the count function is not working
        $fql = “SELECT object_id FROM photo WHERE aid = ‘” . $album_id .“‘ ORDER BY position DESC”;

        //calculatePaging() will give us the paging settings
        //pass the fql and type of object, this is ‘photo’
        $settings = $this->calculatePaging( $fql, ‘photo’ );

        //get start and end limit for the next fql query
        $start_limit = $settings['start_limit'];
        $end_limit = $settings['end_limit'];

        //query the photos
        $fql = “SELECT
                        object_id, pid, src_small, src, src_big, link, caption, created, modified, position, like_info, comment_info
                    FROM
                        photo
                    WHERE
                        aid = ‘” . $album_id .“‘ {$this->excluded_photos}
                    ORDER BY
                        position DESC
                    LIMIT
                        {$start_limit}, {$end_limit}“;

        //set the parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get photos recordset
        $result = $this->facebook->api( $params );

        //add the settings to the result
        $result['pull_fb'] = $settings;

        return $result;
    }

    //to get album cover, you need to pass the cover_id or id of the photo
    public function getAlbumCover( $cover_pid ){

        //get album cover query
        $fql = “select src_big from photo where pid = ‘” . $cover_pid . “‘”;

        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //run the query
        $result = $this->facebook->api( $params );

        //the the value and return it
        $value = $result[0]['src_big'];

        return $value;
    }

    //to get comments, you need to pass the object id, it can be a video, photo, album etc
    //check the fql tables to know object id https://developers.facebook.com/docs/reference/fql/
    public function getComments( $object_id ){

        //query the comment
        $fql = “SELECT
                text, time, fromid, likes
            FROM
                comment
            WHERE
                object_id = “ . $object_id;

        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset
        $result = $this->facebook->api( $params );

        return $result;
    }

    //to get profile name, you need to pass fromid or the profile id
    public function getProfileName( $fromid ){
        //query commenter / profile name
        $fql = “SELECT
                name
            FROM
                profile
            WHERE
                id = “ . $fromid;

        //set the paramters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get the resulting value
        $result = $this->facebook->api( $params );
        $value = $result[0]['name'];

        return $value;
    }

    //this time we will just get the profile name and profile thumbnail
    public function getProfileDetails( $fromid ){

        //select name and pic_square which can be used as profile thumbnail
        $fql = “SELECT
                name, pic_square
            FROM
                profile
            WHERE
                id = “ . $fromid;

        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get and return the result
        $result = $this->facebook->api( $params );

        return $result;
    }

    //to get album name, pass the album id
    public function getAlbumName( $aid ){

        //query album name
        $fql = “SELECT
                name
            FROM
                album
            WHERE
                aid = ‘{$aid}‘”;

        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //return result value for album name
        $result = $this->facebook->api( $params );
        $value = $result[0]['name'];

        return $value;
    }

    //to get events, pass the uid or you fan page id
    public function getEvents( $uid ){
        //query the events
        //we will eid, name, pic_big, start_time, end_time, location, description  this time
        //but there are other data that you can get on the event table (https://developers.facebook.com/docs/reference/fql/event/)
        //as you’ve noticed, we have TWO select statement here
        //since we can’t just do “WHERE creator = your_fan_page_id”.
        //only eid is indexable in the event table, so we have to retrieve
        //list of events by eids
        //and this was achieved by selecting all eid from
        //event_member table where the uid is the id of your fanpage.
        //*yes, you fanpage automatically becomes an event_member
        //once it creates an event
        $fql = “SELECT
                    eid, name, pic_big, start_time, end_time, location, description
                FROM
                    event
                WHERE
                    eid IN ( SELECT eid FROM event_member WHERE uid = {$uid} )
                ORDER BY start_time asc”;

        //set parameters
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset and retur results
        $result = $this->facebook->api($param);
        return $result;
    }

    //this function will get the profile invited to the event
    //pass eid or event id
    public function getEventMembers( $eid ){

        //query the members
        $fql = “SELECT
                    eid, uid, rsvp_status
                FROM
                    event_member
                where eid = {$eid}“;

        //set params
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get result and return it
        $result = $this->facebook->api( $param );
        return $result;
    }

    //get the videos
    //pass the owner or the fan page id
    public function getVideos( $owner ){

        //query to get videos
        //specify you fan page id, I got 221167777906963
        //you can also use the LIMIT clause here if you want to show limited number of videos only
        $fql = “SELECT
                    vid, owner, title, description, thumbnail_link,
                    embed_html, updated_time, created_time, link
                FROM
                    video
                WHERE owner={$owner}“;

        //set parameters
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset and return it
        $result = $this->facebook->api($param);
        return $result;
    }

}
?>

Thanks for reading this [post title here]!

Home Facebook

Display Facebook Data To Website Using PullFb Class

Update: Hi guys! The script on this page is not actively developed anymore, but we have the alternatives! Learn how to display Facebook page data using our links below:

Hi guys! Today I’m going to post about this class I made for pulling data from your Facebook fan page.

In this post we are going to pull data such as photo albums, photos, events, event members, videos and their corresponding likes and comments.

I previously posted about pulling Facebook photos, events and videos with separate but simple methods.

Now this class (pull_fb.class.php), tries to work out all those functions in one with some newly added features.

Display Facebook Data To Website Using PullFb Class

Facebook Database – Facebook API – Your Website

Some people says the old Facebook PHP SDK (2.1.2) don’t work so I used the latest PHP SDK version 3.0.1 that can be downloaded on GitHub. And for this post, the you can download the code I used here:

DOWNLOAD CODE

Facebook Photos

For pulling Facebook albums and photos to website, this version has some new features which includes Facebook like count, comments, comments like count and pagination. Here’s a sample code on how I used the PullFb class to achieve it.

LIVE DEMO

Our index.php code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja – Pull Photos From Facebook</title>
        <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
       
    </head>
<body>

<div style=’font-size: 16px; font-weight: bold; margin: 0 0 10px 0;’>
    This demo is synchronized with this
    <a href=’https://www.facebook.com/pages/COAN-Dummy-Page/221167777906963?sk=photos’>
        Dummy Page Album
    </a>
</div>

<?php
echo “<p>COAN Dummy Page Albums</p>”;

//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//include our class
include ‘pull_fb.class.php’;

//pass appId, appSecret, and page number
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//pass your fan page id
$album_result = $pull_fb->getAlbums( ’221167777906963′ );

//loop through the albums
foreach( $album_result as $key => $value ){
   
    if( trim( $key ) != ‘pull_fb’ ){ //because pull_fb is the settings for paging
   
        //pass album cover photo id to get album cover image
        $album_cover = $pull_fb->getAlbumCover( $value['cover_pid'] );
       
        //display the album details
        echo “<div class=’object_item’>”;
           
            //album cover
            echo “<div class=’field_item’ style=’height:auto;’>”;
                echo “<div class=’lbl’>Album Cover Photo:</div>”;
                echo “<a href=’show_photos.php?aid=” . $value['aid'] . “‘>”;
                    echo “<img src=’$album_cover‘ border=’1′ width=’400px’>”;
                echo “</a>”;
            echo “</div>”;
           
            //album name
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Name:</div>”;
                echo “<div class=’val’>” . $value['name'] . “</div>”;
            echo “</div>”;
           
            //album date created
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Created Date:</div>”;
                echo “<div class=’val’>” . date( ‘l, F d, Y h:i:s A’, $value['created'] ) . “</div>”;
            echo “</div>”;

            //description
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Description:</div>”;
                $description = empty( $value['description'] ) ? “N/A” : $value['description'];
                echo “<div class=’val’>” . $description . “</div>”;
            echo “</div>”;
           
            //where album photos were taken
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Location:</div>”;
                $location = empty( $value['location'] ) ? “N/A” : $value['location'];
                echo “<div class=’val’>” . $location . “</div>”;
            echo “</div>”;
           
            //link to facebook
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album FB Link:</div>”;
                echo “<div class=’val’><a href=’” . $value['link'] . “‘ target=’_blank’>Click Here!</a></div>”;
            echo “</div>”;
           
            //how many photos in the album
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Photo Count:</div>”;
                echo “<div class=’val’>” . $value['photo_count'] . “</div>”;
            echo “</div>”;
           
            //videos included in the album
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Video Count:</div>”;
                echo “<div class=’val’>” . $value['video_count'] . “</div>”;
            echo “</div>”;
           
            //number of likes
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Like Count:</div>”;
                echo “<div class=’val’>” . $value['like_info']['like_count'] . ” people like this album</div>”;
            echo “</div>”;
           
            //number of comments
            echo “<div class=’field_item’ style=’height:auto;’>”;
                echo “<div class=’lbl’>Album Comment Count:</div>”;
                echo “<div class=’val’>” . $value['comment_info']['comment_count'] . ” comments</div>”;
           
            //pass the album object id to get comments
            $comments_result = $pull_fb->getComments( $value['object_id'] );
           
            //loop through comments
            foreach( $comments_result as $key => $value ){
           
                //you can set values to variables
                $text = $value['text'];
                $time = date( ‘l, F d, Y h:i:s A’, $value['time'] );
                $fromid = $value['fromid'];
                $likes = $value['likes'];
               
                //get commenter’s name by passing pass fromid
                $profile_name = $pull_fb->getProfileName( $fromid );
               
                //display the comment details
                echo “<div style=’display:block; text-align:left; float:left; border-bottom:thin solid blue; width:100%;’>”;
                    echo “<div>”;
                   
                        //provide link to commenter’s profile
                        echo “<a href=’https://www.facebook.com/profile.php?id={$fromid}‘ target=’_blank’>”;
                            echo “{$profile_name}“;
                        echo “</a>”;
                        echo ” says:”;
                       
                    echo “</div>”;
                   
                    //display comment
                    echo “<div style=’font-style:italic;’>{$text}</div>”;
                   
                    //the time and number of likes of the comment
                    echo “<div>{$time} | {$likes} people liked this comment</div>”;
                echo “</div>”;
               
            }
           
            echo “<div style=’clear:both;’></div>”;
            echo “</div>”;
        echo “</div>”; //end object_item
        echo “<div style=’clear:both;’></div>”;
    }
   
}

//paging here
//show the page buttons based on the settings returned from getAlbums()
echo “<div style=’font-size:24px;’>”;
    //paging here  
    if( $value['prev_button'] ){
        echo “<a href=’index.php?page=1′>&#9668;&#9668; First</a> “;
        echo “<a href=’index.php?page={$value['prev_page']}‘>&#9668; Previous</a> “;
    }
   
    if( $value['next_button'] ){
        echo “<a href=’index.php?page={$value['next_page']}‘>Next &#9658;</a> “;
        echo “<a href=’index.php?page={$value['last_page']}‘>Last &#9658;&#9658;</a>”;
    }
echo “</div>”;

?>

  </body>
</html>

Our show_photos.php code

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja – Pull Data From Facebook</title>
        <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
       
    </head>
<body>

<div style=’font-size: 16px; font-weight: bold; margin: 0 0 10px 0;’>
    This demo is synchronized with this
    <a href=’https://www.facebook.com/pages/COAN-Dummy-Page/221167777906963?sk=photos’>
        Dummy Page Album
    </a>
</div>

<?php
//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//get album id from the url
$album_id = empty( $_REQUEST['aid'] ) ? die( “Album ID cannot be empty” ) : $_REQUEST['aid'];

//include our class
include ‘pull_fb.class.php’;
   
//pass appId, appSecret, and page number
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//get the album name based on album id
$album_name = $pull_fb->getAlbumName( $album_id );

//provide link to albums
echo “<div><a href=’http://demo.codeofaninja.com/tutorials/pull-facebook-data/’>Back To Albums</a> | Album Name: <b>” . $album_name . “</b></div>”;

//get photos of the album
$photos_result = $pull_fb->getPhotos( $album_id );

//loop through the photos
foreach( $photos_result as $key => $value ){
   
    if( trim( $key ) != ‘pull_fb’ ){ //because pull_fb is the settings
   
        //set caption to ‘None.’ if no caption was set
        $caption = !empty( $value['caption'] ) ? $value['caption'] : “None.”;
       
        //display the photo details
        echo “<div class=’object_item’>”;
       
            //the photo
            echo “<div class=’field_item’ style=’height:auto;’>”;
                echo “<div class=’lbl’>Photo:</div>”;
                echo “<a href=““ . $value['src_big'] . ““ title=““ . $caption . ““ rel=’lightbox’>”;
                    echo “<img src=’” . $value['src_big'] . “‘ border=’1′ width=’400px’ />”;
                echo “</a>”;
            echo “</div>”;
           
            //caption
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Photo ID:</div>”;
                echo “<div class=’val’>” . $value['pid'] . “</div>”;
            echo “</div>”;
           
            //caption
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Caption:</div>”;
                echo “<div class=’val’>” . $caption . “</div>”;
            echo “</div>”;
           
            //date created
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Created Date:</div>”;
                echo “<div class=’val’>” . date( ‘l, F d, Y’, $value['created'] ) . “</div>”;
            echo “</div>”;

            //date modified
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Modified Date:</div>”;
                echo “<div class=’val’>” . date( ‘l, F d, Y’, $value['modified'] ) . “</div>”;
            echo “</div>”;
           
            //photo position in the album
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Photo Position:</div>”;
                echo “<div class=’val’>” . $value['position'] . “</div>”;
            echo “</div>”;
           
            //link to facebook
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album FB Link:</div>”;
                echo “<div class=’val’>”;
                    echo “<a href=’” . $value['link'] . “‘ target=’_blank’>Click Here!</a>”;
                echo “</div>”;
            echo “</div>”;
           
            //number of likes
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Like Count:</div>”;
                echo “<div class=’val’>” . $value['like_info']['like_count'] . ” people like this</div>”;
            echo “</div>”;
           
            //number of comments
            echo “<div class=’field_item’ style=’height:auto;’>”;
                echo “<div class=’lbl’>Album Comment Count:</div>”;
                echo “<div class=’val’>” . $value['comment_info']['comment_count'] . ” comments</div>”;
               
                //pass the object id to get comments of this photo
                $comments_result = $pull_fb->getComments( $value['object_id'] );
               
                //loop through retrieved comments
                foreach( $comments_result as $key => $value ){
               
                    //you can set the values to variables
                    $text = $value['text'];
                    $time = date( ‘l, F d, Y h:i:s A’, $value['time'] );
                    $fromid = $value['fromid'];
                    $likes = $value['likes'];
                   
                    //get commenter’s name by passing pass fromid
                    $profile_name = $pull_fb->getProfileName( $fromid );
                   
                    //display the comment details
                    echo “<div style=’display:block; text-align:left; float:left; border-bottom:thin solid blue; width:100%;’>”;
                        echo “<div>”;
                            //provide link to commenter’s profile
                            echo “<a href=’https://www.facebook.com/profile.php?id={$fromid}‘ target=’_blank’>”;
                                echo “{$profile_name}“;
                            echo “</a>”;
                            echo ” says:”;
                        echo “</div>”;
                       
                        //display comment
                        echo “<div style=’font-style:italic;’>{$text}</div>”;
                       
                        //the time and number of likes of the comment
                        echo “<div>{$time} | {$likes} people liked this comment</div>”;
                    echo “</div>”;
                   
                }
               
                echo “<div style=’clear:both;’></div>”;
               
            echo “</div>”;
           
        echo “</div>”;
   
    }
   
}

    //paging here
    //show the page buttons based on the settings returned from getPhotos()
    echo “<div style=’font-size:24px;’>”;
       
        if( $value['prev_button'] ){
            echo “<a href=’show_photos.php?aid={$_GET['aid']}&page=1′>&#9668;&#9668; First</a> “;
            echo “<a href=’show_photos.php?aid={$_GET['aid']}&page={$value['prev_page']}‘>&#9668; Previous</a> “;
        }
       
        if( $value['next_button'] ){
            echo “<a href=’show_photos.php?aid={$_GET['aid']}&page={$value['next_page']}‘>Next &#9658;</a> “;
            echo “<a href=’show_photos.php?aid={$_GET['aid']}&page={$value['last_page']}‘>Last &#9658;&#9658;</a>”;
        }
    echo “</div>”;
   
?>

    <!– START JLIGHTBOX –>
   
    <link rel=”stylesheet” type=”text/css” href=”jQuery-lightbox/css/jquery.lightbox-0.5.css” media=”screen” />
    <script type=”text/javascript” src=”jQuery-lightbox/js/jquery.js”></script>
    <script type=”text/javascript” src=”jQuery-lightbox/js/jquery.lightbox-0.5.js”></script>
   
    <script type=”text/javascript”>
   
        $(function() {
            $(‘a[@rel*=lightbox]‘).lightBox(); // Select all links that contains lightbox in the attribute rel
        });
   
    </script>
   
    <!– END JLIGHTBOX –>
   
  </body>
</html>

Facebook Events

For pulling Facebook events, it features pulling the event members and their corresponding RSVP status. As for the paging, maybe you can do the same approach I used in pulling Facebook albums and photos.

LIVE DEMO

Our show_events.php code:

<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”
    xmlns:fb=”http://www.facebook.com/2008/fbml”>
        <head>
            <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
            <title>The Code Of A Ninja – Pull Events From Facebook</title>
            <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
            <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
        </head>
<body>
<?php

//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//we have to set timezone to California
date_default_timezone_set(‘America/Los_Angeles’);

//include our class
include ‘pull_fb.class.php’;

//pass appId, appSecret, and page number
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//just a heading
echo “<div style=’font-weight: bold; margin: 0 0 20px 0;’>”;
echo “This event list is synchronized with this “;
echo “<a href=’https://www.facebook.com/pages/COAN-Dummy-Page/221167777906963?sk=events’>”;
echo “COAN Dummy Page Events</a></div>”;

//pass your fan page id
$event_result = $pull_fb->getEvents( ’221167777906963′ );

//looping through retrieved data
foreach( $event_result as $key => $value ){

    //see here http://php.net/manual/en/function.date.php for the date format I used
    //The pattern string I used ‘l, F d, Y g:i a’
    //will output something like this: July 30, 2015 6:30 pm

    //getting ‘start’ and ‘end’ date,
    //’l, F d, Y’ pattern string will give us
    //something like: Thursday, July 30, 2015
    $start_date = date( ‘l, F d, Y’, $value['start_time'] );
    $end_date = date( ‘l, F d, Y’, $value['end_time'] );

    //getting ‘start’ and ‘end’ time
    //’g:i a’ will give us something
    //like 6:30 pm
    $start_time = date( ‘g:i a’, $value['start_time'] );
    $end_time = date( ‘g:i a’, $value['end_time'] );

    //display the album details
    echo “<div class=’object_item’>”;
   
    //event image
    echo “<div style=’float: left; margin: 0 8px 0 0;’>”;
            echo “<img src={$value['pic_big']} />”;
    echo “</div>”;
       
        echo “<div style=’float: left;’>”;
           
            //event name
            echo “<div class=’field_item’>”;
                echo “<div class=’val’ style=’font-size: 26px’>”;
                    echo “<a href=’https://www.facebook.com/events/{$value['eid']}/’ target=’_blank’>”;
                        echo $value['name'];
                    echo “</a>”;
                echo “</div>”;
            echo “</div>”;
           
            //event date / time
            echo “<div class=’field_item’>”;
                echo “<div class=’val’>”;
                if( $start_date == $end_date ){
                        //if $start_date and $end_date is the same
                        //it means the event will happen on the same day
                        //so we will have a format something like:
                        //July 30, 2015 – 6:30 pm to 9:30 pm
                        echo “on {$start_date} – {$start_time} to {$end_time}“;
                }else{
                        //else if $start_date and $end_date is NOT the equal
                        //it means that the event will will be
                        //extended to another day
                        //so we will have a format something like:
                        //July 30, 2013 9:00 pm to Wednesday, July 31, 2013 at 1:00 am
                        echo “on {$start_date} {$start_time} to {$end_date} at {$end_time}“;
                }
                echo “</div>”;
            echo “</div>”;
           
            //event location
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Location:</div>”;
                echo “<div class=’val’>” . $value['location'] . “</div>”;
            echo “</div>”;
           
            //event description
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>More Info:</div>”;
                echo “<div class=’val’>” . $value['description'] . “</div>”;
            echo “</div>”;
       
            echo “<div style=’clear: both’></div>”;
           
            //get people invited to the event
            $event_members = $pull_fb->getEventMembers( $value['eid'] );
           
            //loop through event members
            foreach( $event_members as $event_member ){
           
                //get profile pic and name of the event member
                $result = $pull_fb->getProfileDetails( $event_member['uid'] );
                $pic_square = $result[0]['pic_square'];
                $name = $result[0]['name'];
               
                //display event member details
                echo “<div style=’padding:8px 0; text-align:left;’>”;
               
                    //small square profile pic
                    echo “<div style=’float:left; width:40px;’>”;
                        echo “<img src=’{$pic_square}‘ width=’30px’ height=’30px’ />”;
                    echo “</div>”;
                   
                    //provide link to event member profile
                    echo “<div>Name: “;
                        echo “<a href=’https://www.facebook.com/profile.php?id={$event_member['uid']}‘ target=’_blank’>”;
                            echo $name;
                        echo “</a>”;
                    echo “</div>”;
                   
                    //rsvp status
                    echo “<div>RSVP Status: {$event_member['rsvp_status']}</div>”;
                   
                echo “</div>”;
            }
           
        echo “</div>”;
   
    echo “<div style=’clear: both’></div>”;
   
    echo “</div>”;
       
}

?>
</body>
</html>

Facebook Videos

For pulling Facebook videos, it features pulling the comments and likes. As for the paging, maybe you can do the same approach I used in pulling Facebook albums and photos.

LIVE DEMO

Our show_videos.php code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja – Pull Videos From Facebook</title>
        <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
    </head>
<body>

<div class=’page_title’>
    These videos are synchronized with this
    <a href=’https://www.facebook.com/video/?id=221167777906963′ target=’_blank’>
        Dummy Page Videos
    </a>
</div>
<?php

//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//include our class
include ‘pull_fb.class.php’;

//pass appId, appSecret, and page number
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//pass your fan page id
$videos_result = $pull_fb->getVideos( ’221167777906963′ );

//loop through each videos
foreach( $videos_result as $keys => $value ){
   
    //display video details
    echo “<div class=’object_item’>”;
   
        //video embed html
        echo $value['embed_html'];
       
        //video title
        echo “<div class=’field_item’>”;
            echo “<div class=’lbl’>Title:</div>”;
            echo “<div class=’val’>” . $value['title'] . “</div>”;
        echo “</div>”;
       
        //date created
        echo “<div class=’field_item’>”;
            echo “<div class=’lbl’>Date Created:</div>”;
            echo “<div class=’val’>” . date( ‘l, F d, Y’, $value['created_time'] ) . “</div>”;
        echo “</div>”;
       
        //video description
        echo “<div class=’field_item’>”;
            echo “<div class=’lbl’>Description:</div>”;
            echo “<div class=’val’>” . $value['description'] . “</div>”;
        echo “</div>”;
       
        //fb link to video
        echo “<div class=’field_item’>”;
            echo “<div class=’lbl’>FB Link:</div>”;
            echo “<div class=’val’><a href=’” . $value['link'] . “‘ target=’_blank’>Click Here!</a></div>”;
        echo “</div>”;
                   
        echo “<div class=’field_item’ style=’height:auto;’>”;
       
        //vid is the object id of video, pass to get the comments
        $comments_result = $pull_fb->getComments( $value['vid'] );
       
        //loop through comments
        foreach( $comments_result as $key => $value ){
       
            //you can set values to variables
            $text = $value['text'];
            $time = date( ‘l, F d, Y h:i:s A’, $value['time'] );
            $fromid = $value['fromid'];
            $likes = $value['likes'];
           
            //get commenter’s name by passing pass fromid
            $profile_name = $pull_fb->getProfileName( $fromid );
           
            //display the comment details
            echo “<div style=’display:block; text-align:left; float:left; border-bottom:thin solid blue; width:100%;’>”;
                echo “<div>”;
                    //provide link to commenter’s profile
                    echo “<a href=’https://www.facebook.com/profile.php?id={$fromid}‘ target=’_blank’>”;
                        echo “{$profile_name}“;
                    echo “</a>”;
                    echo ” says:”;
                echo “</div>”;
               
                //display comment
                echo “<div style=’font-style:italic;’>{$text}</div>”;
               
                //the time and number of likes of the comment
                echo “<div>{$time} | {$likes} people liked this comment</div>”;
            echo “</div>”;
           
        }

        echo “<div style=’clear:both;’></div>”;
        echo “</div>”;
        echo “</div>”;
    echo “</div>”;
   
}

?>
   
  </body>
</html>

June 9, 2012 Update: Display Facebook Feed on Website

PullFB Class

Now here’s the code of our class pull_fb.class.php

<?php
require ‘fb-sdk/src/facebook.php’;

class PullFb{
   
    //set properties
    public $facebook;
    public $page_num;
   
    //number of items you want to see per page
    //you can add for other objects such as videos, etc.
    public $albums_per_page = 2;
    public $photos_per_page = 4;
   
    //if you want to exclude some albums like the Profile Pictures and Wall Photos, do something like:
    //$excluded_albums = “AND name <> ‘Profile Pictures’ AND name <> ‘Wall Photos’”;
    //in my example, I’m gonna exclude the wall photos only
    public $excluded_albums = “AND name <> ‘Wall Photos’”;
   
    //same with excluding photos, just state the pid
    public $excluded_photos = “AND pid <> ’221167777906963_1513599′ AND pid <> ’221167777906963_1513596′”;
   
    public function __construct( $appId, $secret, $page_num ){
       
        //create facebook instance
        $this->facebook = new Facebook(array(
          ‘appId’  => $appId,
          ‘secret’ => $secret,
          ‘cookie’ => true, // enable optional cookie support
        ));
       
        //for the page number
        $this->page_num = $page_num;
    }
   
    //this will get facebook albums based on the $owner or fan page id
    public function getAlbums( $owner ){
       
        //we have to get the total number of albums first
        //i don’t know why the count function is not working
        $fql = “SELECT aid FROM album WHERE owner = {$owner} {$this->excluded_albums}“;
       
        //calculatePaging() will give us the paging settings
        //pass the fql and type of object
        $settings = $this->calculatePaging( $fql, ‘album’ );
       
        //get start and end limit for the next fql query
        $start_limit = $settings['start_limit'];
        $end_limit = $settings['end_limit'];
       
        //in this query we will include the paging based on the page number
        $fql = “SELECT
                    aid, object_id, owner, cover_pid, cover_object_id, name, created, modified,
                    description, location, size, link, visible, modified_major, edit_link,
                    type, can_upload, photo_count, video_count,
                    like_info, comment_info
                FROM
                    album
                WHERE
                    owner = {$owner} {$this->excluded_albums}
                LIMIT
                    {$start_limit}, {$end_limit}“;
                   
        //set params
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get recordset
        $result = $this->facebook->api( $params );
       
        //we will include the settings to our result variable
        $result['pull_fb'] = $settings;
       
        return $result;
    }

    //this function was made for paging
    public function calculatePaging( $fql, $type ){
   
        //set the params based on passed fql
        //to count the total number of records
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get recordset
        $result = $this->facebook->api( $params );
       
        //get the total number of items
        $number_of_items = count( $result );
       
        //we will have the following calculations for the pagination
        //we just need some simple math
       
        //decide how many albums to show per page
        //values was actually declared as class property
        //you can easily add for other types of object
        if( $type == ‘album’ ){
            $items_per_page = $this->albums_per_page;
        }else if( $type == ‘photo’ ){
            $items_per_page = $this->photos_per_page;
        }
       
        //this is the current page
        $curr_page = $this->page_num;
       
        //previous page will be the current page MINUS one
        $prev_page = $curr_page - 1;
       
        //next page will be the current page PLUS one
        $next_page = $curr_page + 1;
       
        //no need to calculate for the first page, obviously, it’s 1
        //calculate last page
        $last_page = round( $number_of_items / $items_per_page );
       
        //detect if prev button will be visible
        if( $curr_page != 1 ){
            $prev_button = true;
        }
       
        //get $albums_shown value
        //it is the number of photos from the first page up to the current page
        $items_shown = $items_per_page * $curr_page;
       
        //detect if next button will be visible
        //if the $number_of_albums were still higher than the $albums_shown, show the next page button,
        //but if they are equal, don’t show the next page button
        if( $number_of_items > $items_shown ){
            $next_button = true;
        }
       
        //get start limit for the fql query
        $start_limit = $items_per_page * $prev_page;
       
        //get end limit
        //i’m not sure why i had to + 1, maybe it’s a facebook bug?
        $end_limit = $items_per_page + 1;
       
        //these are the values or settings returned
        //i made it to an array
        $settings = array(
            ‘number_of_items’ => $number_of_items,
            ‘prev_page’ => $prev_page,
            ‘next_page’ => $next_page,
            ‘prev_button’ => $prev_button,
            ‘next_button’ => $next_button,
            ‘start_limit’ => $start_limit,
            ‘end_limit’ => $end_limit,
            ‘last_page’ => $last_page
        );
       
        return $settings;
    }
   
    //to get photos of an album, we have to pass the album id
    public function getPhotos( $album_id ){

        //we have to get total number of photos first
        //i don’t know why the count function is not working
        $fql = “SELECT object_id FROM photo WHERE aid = ‘” . $album_id .“‘ ORDER BY position DESC”;
       
        //calculatePaging() will give us the paging settings
        //pass the fql and type of object, this is ‘photo’
        $settings = $this->calculatePaging( $fql, ‘photo’ );
       
        //get start and end limit for the next fql query
        $start_limit = $settings['start_limit'];
        $end_limit = $settings['end_limit'];
       
        //query the photos
        $fql = “SELECT
                        object_id, pid, src_small, src, src_big, link, caption, created, modified, position, like_info, comment_info
                    FROM
                        photo
                    WHERE
                        aid = ‘” . $album_id .“‘ {$this->excluded_photos}
                    ORDER BY
                        position DESC
                    LIMIT
                        {$start_limit}, {$end_limit}“;
       
        //set the parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get photos recordset
        $result = $this->facebook->api( $params );
       
        //add the settings to the result
        $result['pull_fb'] = $settings;
       
        return $result;
    }
   
    //to get album cover, you need to pass the cover_id or id of the photo
    public function getAlbumCover( $cover_pid ){
   
        //get album cover query
        $fql = “select src_big from photo where pid = ‘” . $cover_pid . “‘”;
       
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //run the query
        $result = $this->facebook->api( $params );
       
        //the the value and return it
        $value = $result[0]['src_big'];
       
        return $value;
    }
   
    //to get comments, you need to pass the object id, it can be a video, photo, album etc
    //check the fql tables to know object id https://developers.facebook.com/docs/reference/fql/
    public function getComments( $object_id ){
   
        //query the comment
        $fql = “SELECT
                text, time, fromid, likes
            FROM
                comment
            WHERE
                object_id = “ . $object_id;
       
        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get recordset
        $result = $this->facebook->api( $params );
       
        return $result;
    }
   
    //to get profile name, you need to pass fromid or the profile id
    public function getProfileName( $fromid ){
        //query commenter / profile name
        $fql = “SELECT
                name
            FROM
                profile
            WHERE
                id = “ . $fromid;
       
        //set the paramters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get the resulting value
        $result = $this->facebook->api( $params );
        $value = $result[0]['name'];
       
        return $value;
    }
   
    //this time we will just get the profile name and profile thumbnail
    public function getProfileDetails( $fromid ){
   
        //select name and pic_square which can be used as profile thumbnail
        $fql = “SELECT
                name, pic_square
            FROM
                profile
            WHERE
                id = “ . $fromid;
       
        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get and return the result
        $result = $this->facebook->api( $params );
       
        return $result;
    }
   
    //to get album name, pass the album id
    public function getAlbumName( $aid ){
   
        //query album name
        $fql = “SELECT
                name
            FROM
                album
            WHERE
                aid = ‘{$aid}‘”;
       
        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //return result value for album name
        $result = $this->facebook->api( $params );
        $value = $result[0]['name'];
       
        return $value;
    }
   
    //to get events, pass the uid or you fan page id
    public function getEvents( $uid ){
        //query the events
        //we will eid, name, pic_big, start_time, end_time, location, description  this time
        //but there are other data that you can get on the event table (https://developers.facebook.com/docs/reference/fql/event/)
        //as you’ve noticed, we have TWO select statement here
        //since we can’t just do “WHERE creator = your_fan_page_id”.
        //only eid is indexable in the event table, so we have to retrieve
        //list of events by eids
        //and this was achieved by selecting all eid from
        //event_member table where the uid is the id of your fanpage.
        //*yes, you fanpage automatically becomes an event_member
        //once it creates an event
        $fql = “SELECT
                    eid, name, pic_big, start_time, end_time, location, description
                FROM
                    event
                WHERE
                    eid IN ( SELECT eid FROM event_member WHERE uid = {$uid} )
                ORDER BY start_time asc”;
                               
        //set parameters
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset and retur results
        $result = $this->facebook->api($param);
        return $result;
    }
   
    //this function will get the profile invited to the event
    //pass eid or event id
    public function getEventMembers( $eid ){
       
        //query the members
        $fql = “SELECT
                    eid, uid, rsvp_status
                FROM
                    event_member
                where eid = {$eid}“;
       
        //set params
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get result and return it
        $result = $this->facebook->api( $param );
        return $result;
    }
   
    //get the videos
    //pass the owner or the fan page id
    public function getVideos( $owner ){
   
        //query to get videos
        //specify you fan page id, I got 221167777906963
        //you can also use the LIMIT clause here if you want to show limited number of videos only
        $fql = “SELECT
                    vid, owner, title, description, thumbnail_link,
                    embed_html, updated_time, created_time, link
                FROM
                    video
                WHERE owner={$owner}“;
                   
        //set parameters
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get recordset and return it
        $result = $this->facebook->api($param);
        return $result;
    }
   
}
?>

This class can be easily modified or extend depending on your needs. You can play around different Facebook tables. Thanks for all your comments, suggestions, catches and contributions from the previous version. Feel free to do that again. :)

Regarding “Headers already sent…” issues, you can learn more fixing that here.

Note: A lot of you is trying this script in localhost, I think this won’t work. Please use this script on your real web host or buy from this bluehost link. Thanks!

Home JavaScript

Move Options Between Two Select Boxes

Today we are going to do a code that can move options between two select boxes and save the changes to the database.

I think this functionality will improve the user experience since the interface is intuitive.

In this example, we are going to have the first select box (left side) which contains the list or data of available objects, the buttons that will make the options move either to the left or right, the second select box (right side) which contains the list of assigned objects, and of course, the save button.

See my video demo here:

assigned_objects table – this will be used to store the ids of assigned objects.

CREATE TABLE IF NOT EXISTS `assigned_objects` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` int(11) NOT NULL COMMENT ‘1=user,2=location’,
  `object_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
)

locations table – this will be used to store the location objects

—
— Table structure for table `locations`
—
CREATE TABLE IF NOT EXISTS `locations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

—
— Dumping data for table `locations`
—

INSERT INTO `locations` (`id`, `name`) VALUES
(1, ‘Cavite’),
(2, ‘Laguna’),
(3, ‘Batangas’),
(4, ‘Rizal’),
(5, ‘Quezon’),
(6, ‘Antiipolo’),
(7, ‘Capiz’),
(8, ‘Boracay’),
(9, ‘Mindoro’),
(10, ‘Novaliches’);

Our index.php code:

<html>
    <head>
        <title>Move Options Between Two Select Boxes And Save Changes To Database</title>
        <!– include some style –>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
    </head>
<body>
<?php
//connect to database
include ‘db_connect.php’;

//if the form was submitted
if( $_POST ){

    //delete previously assigned locations
    //in this example, type = 2 means “location”
    $sql = “delete from assigned_objects where type = 2”;
    
    //execute the sql
    if( $mysqli->query( $sql ) ){
    
        //if the query was executed successfully
        //save newly assigned names
        //$_POST[‘location_right’] is the select box on the right side
        foreach( $_POST[‘location_right’] as $value ){
            
            //write save query
            $sql = “insert into assigned_objects ( type, object_id ) 
                        values( 2, “ . $mysqli->real_escape_string( $value ) . ” )”;

            //execute save sql query
            if( !( $mysqli->query( $sql ) ) ){
                
                //if the query execution was unsuccessful
                echo “<div>Database Error: Unable to insert record.</div>”;
            }
            
        }
        
    }else{
        //if unable to delete previously assigned locations
        echo “<div>Database Error: Unable to delete assigned locations.</div>”;
    }
    
}

//get ids of currently assigned locations 
$sql = “select * from assigned_objects where type = 2”;
$result = $mysqli->query( $sql );

if( $result ){
    
    //$location_in will be our variable to accumulate currently assigned locations ids
    //example value will be “46, 49, 51”, 
    //which will be used to exempt currently assigned locations (right select box) 
    //to available locations list (left select box)
    $location_in = “”;
    
    //get number of rows found
    $num = $result->num_rows;
    
    if( $num ){ //if there are assigned locations in the database
    
        //set $x to 1, the first loop
        $x = 1;
        
        while( $row = $result->fetch_assoc() ){ //loop the accumulate values
        
            //object_id is actually the location id
            $location_in .= $row[‘object_id’];
            
            //when $x is less than the total number of rows, append a comma
            //else, do not append a comma
            if( $x < $num ){
                $location_in .= “, “;
            }
            
            //increment $x
            $x++;
        }
        
    }

}else{
    //when there’s an error selecting the assigned locations
    echo “Database Error: Unable to select assigned locations.”;
}

?>

<div>

<!–
    here on our form, the onsubmit value is very important,
    it will select all the values in the location_right select box,
    which is to be saved in the database.
    see the javascript section for details about selectAll()
–>
<form action=’index.php’ method=’post’ onsubmit=”return selectAll( new Array( ‘location_right’ ) );”>

    <!– left select box –>
    <div class=’select_box’>
        <div class=’select_title’>Available Locations</div>
        <div style=’clear:both;’></div>
        <select name=’location_left’ id=’location_left’ size=’7′ multiple=’multiple’>
            <?php
            
            if( $location_in ){ //if $location_id has a value, there are location ids to be exempted
                $sql = “select * from locations where id not in ( {$location_in} ) order by name”; 
            }else{
                //else, select all locations
                $sql = “select * from locations”; 
            }
            
            $result = $mysqli->query( $sql );

            if( $result ){
                //if it returns a result, loop through it with options tag
                while( $row = $result->fetch_assoc() ){
                    echo “<option value=’{$row[‘id’]}‘>{$row[‘name’]}</option>”;
                }
            }
            ?>
        </select>
    </div>

    <!– direction move buttons –>
    <div class=’btn’>
        <!– option move to right button –>
        <button type=”button” onclick=”move( ‘location_left’, ‘location_right’ )”> > </button>
        <br />
        <!– option move to left button –>
        <button type=”button” onclick=”move( ‘location_right’, ‘location_left’ )”> < </button>
    </div>

    <!– right select box –>
    <div class=’select_box’>
        <div class=’select_title’>Assigned Locations</div>
        <div style=’clear:both;’></div>
        <select name=’location_right[]’ id=’location_right’ size=’7′ multiple=’multiple’>
        
            <?php       
            //query joining assigned_objects and locations table
            //so we can easily get the location_name
            $sql = “select
                        l.id as location_id, 
                        l.name as location_name 
                    from 
                        assigned_objects ao, locations l
                    where 
                        ao.type = 2 
                        and ao.object_id in ( {$location_in} )
                        and ao.object_id = l.id”;
                    
            $result = $mysqli->query( $sql );

            if( $result ){
                //if query successful, loop through the values with option tag
                //so it will show up in the select list
                while( $row = $result->fetch_assoc() ){
                    
                    echo “<option value=’{$row[‘location_id’]}‘>{$row[‘location_name’]}</option>”;
                
                }
            }
            
            ?>
        </select>
        
    </div>
    
    <div style=’clear:both;’></div>
    <input type=’submit’ value=’Save’ />
    
</form>

<script type=’text/javascript’>
//this function will select all the values of the right select box, so you can post it
//this function can accept array of select boxes with id as its reference
function selectAll( obj_arr ){

    var obj_sel;
    for ( var i = 0; i < obj_arr.length; i++ ){
    
        obj_sel = document.getElementById( obj_arr[i] );
        
        for( var j = 0; j < obj_sel.options.length; j++ ){
            obj_sel.options[j].selected = true;
        }
        
    }
    
}

function move( id_1, id_2 ){
        
        //the box where the value will come from
        var opt_obj = document.getElementById( id_1 );
        
        //the box where the value will be locationd
        var sel_obj = document.getElementById( id_2 );
        
        for ( var i = 0; i < opt_obj.options.length; i++ ){ //loop to check for multiple selections
                
                if ( opt_obj.options[i].selected == true ){ //check if the option was selected
                        
                        //value to be transfered
                        var selected_text = opt_obj.options[i].text;
                        var selected_value = opt_obj.options[i].value;
                        
                        //remove from opt
                        opt_obj.remove( i );
                        
                        //decrease value of i since an option was removed 
                        //therefore the opt_obj.options.length will also decrease
                        i–;
                        
                        //process to sel
                        var new_option_index = sel_obj.options.length;
                        sel_obj.options[new_option_index] = new Option( selected_text, selected_value );
                        
                }
                
        }
}
        
</script>

</body>
</html>

I have another example here that uses two objects which are users and locations. See my video demo:

users table – this will be used to store the user objects.

—
— Table structure for table `users`
—
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=55 ;

—
— Dumping data for table `users`
—

INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `username`, `password`, `modified`) VALUES
(28, ‘John’, ‘Dalisay’, ”, ‘john’, ‘john123’, ‘2012-01-15 15:26:14’),
(39, ‘Jemski’, ‘Panlilios’, ‘jemboy@gmail.com’, ‘jemboy09’, ‘jem123’, ‘2012-03-17 23:20:05’),
(40, ‘Darwin’, ‘Dalisay’, ”, ‘dada08’, ‘dada123’, ‘2012-01-15 15:25:34’),
(46, ‘Jaylord’, ‘Bitamug’, ”, ‘jayjay’, ‘jay123’, ‘2012-01-15 15:27:04’),
(49, ‘Justine’, ‘Bongola’, ”, ‘jaja’, ‘jaja123’, ‘2012-01-15 15:27:21’),
(50, ‘Jun’, ‘Sabayton’, ”, ‘jun’, ‘jun123’, ‘2012-02-05 18:15:14’),
(51, ‘Lourd’, ‘De Veyra’, ”, ‘lourd’, ‘lourd123’, ‘2012-02-05 18:15:36’),
(52, ‘Asi’, ‘Taulava’, ”, ‘asi’, ‘asi123’, ‘2012-02-05 18:15:58’),
(53, ‘James’, ‘Yap’, ”, ‘james’, ‘jame123’, ‘2012-02-05 18:16:17’),
(54, ‘Chris’, ‘Tiu’, ”, ‘chris’, ‘chris123’, ‘2012-04-11 17:16:29’);

The code download is included in the download link above of this post. I have written this code few years ago with MySQL, but you can easily convert it to MySQLi or PDO though. Here’s the mysql_index.php code:

<html>
        <head>
                <title>Move Options Between Two Select Boxes</title>
                
                <style type=’text/css’>
                        select{
                                width:200px;
                        }
                        
                        .select_box{
                                float:left;
                                margin:0 0 20px 0;
                        }
                        
                        .btn{
                                float:left;
                                margin:20px;
                        }
                </style>
        </head>
<body>
<?php
//connect to database
include ‘mysql_db_connect.php’;

if( $_POST ){

    //delete previously assigned names
    $sql = “delete from assigned_objects where type = 1”;
    mysql_query( $sql );
    
    //save newly assigned names
    foreach( $_POST[‘name_right’] as $value ){
        
        $sql = “insert into assigned_objects ( type, object_id ) values( 1, {$value} )”;
        mysql_query( $sql );
        
    }
    
    //delete previously assigned locations
    $sql = “delete from assigned_objects where type = 2”;
    mysql_query( $sql );
    
    //save newly assigned locations
    foreach( $_POST[‘location_right’] as $value ){
        
        $sql = “insert into assigned_objects ( type, object_id ) values( 2, {$value} )”;
        mysql_query( $sql );
        
    }
    
}

//(name) prepare id values for IN
$sql = “select * from assigned_objects where type = 1”;
$rs = mysql_query( $sql );

$in = “”;
$x = 1;
$num = mysql_num_rows( $rs );

if( $num ){
    while( $row = mysql_fetch_array( $rs ) ){
        extract( $row );
        $in .= $object_id;
        
        if( $x < $num ){
            $in .= “, “;
        }
        
        $x++;
    }
}

//(location) prepare id values for IN
$sql = “select * from assigned_objects where type = 2”;
$rs = mysql_query( $sql );

$location_in = “”;
$x = 1;
$num = mysql_num_rows( $rs );

if( $num ){
    while( $row = mysql_fetch_array( $rs ) ){
        extract( $row );
        $location_in .= $object_id;
        
        if( $x < $num ){
            $location_in .= “, “;
        }
        
        $x++;
    }
}
?>

<!–
    here on our form, the onsubmit value is very important,
    it will select all the values in the location_right select box,
    which is to be saved in the database.
    see the javascript section for details about selectAll()
–>
<form action=’#’ method=’post’ onsubmit=”return selectAll( new Array( ‘name_right’, ‘location_right’ ) );”>

    <!– left select box –>
    <div class=’select_box’>
        <div class=’select_title’>Available Users</div>
        <div style=’clear:both;’></div>
        <select name=’name_left’ id=’name_left’ size=’7′ multiple=’multiple’>
        
            <?php
            
            if( $in ){ //if $in has a value, there are location ids to be exempted
                $sql = “select * from users where id not in ( {$in} ) order by firstname”; 
            }else{
                //else select all users
                $sql = “select * from users”; 
            }
            
            $rs = mysql_query( $sql );
            
            while( $row = mysql_fetch_array( $rs ) ){
                extract( $row );
                echo “<option value=’{$id}‘>{$firstname} {$lastname}</option>”;
            }
            
            ?>
        </select>
    </div>

        <!– direction move buttons –>
        <div class=’btn’>
            <!– move to right button –>
            <button type=”button” onclick=”move( ‘name_left’, ‘name_right’ )”> > </button>
            <br />
            <!– move to left button –>
            <button type=”button” onclick=”move( ‘name_right’, ‘name_left’ )”> < </button>
        </div>

    <!– right select box –>
    <div class=’select_box’>
        <div class=’select_title’>Assigned Users</div>
        <div style=’clear:both;’></div>
        <select name=’name_right[]’ id=’name_right’ size=’7′ multiple=’multiple’>
        
            <?php       
            
            $sql = “select
                        u.id as user_id, 
                        u.firstname as fn,
                        u.lastname as ln
                    from 
                        assigned_objects ao, users u
                    where 
                        ao.type = 1
                        and ao.object_id in ( {$in} )
                        and ao.object_id = u.id”;
            $rs = mysql_query( $sql );
            
            while( $row = mysql_fetch_array( $rs ) ){
                
                echo “<option value=’{$row[‘user_id’]}‘>{$row[‘fn’]} {$row[‘ln’]}</option>”;
                
            }
            
            ?>
        </select>
        
    </div>

    <div style=’clear:both;’></div>

    <!– left select box –>
    <div class=’select_box’>
        <div class=’select_title’>Available Locations</div>
        <div style=’clear:both;’></div>
        <select name=’location_left’ id=’location_left’ size=’7′ multiple=’multiple’>
            <?php
            
            if( $location_in ){
                $sql = “select * from locations where id not in ( {$location_in} ) order by name”; 
            }else{
                $sql = “select * from locations”; 
            }
            
            $rs = mysql_query( $sql );
            
            while( $row = mysql_fetch_array( $rs ) ){
                extract( $row );
                echo “<option value=’{$row[‘id’]}‘>{$row[‘name’]}</option>”;
            }
            
            ?>
        </select>
    </div>

        <!– direction move buttons –>
        <div class=’btn’>
            <!– move to right button –>
            <button type=”button” onclick=”move( ‘location_left’, ‘location_right’ )”> > </button>
            <br />
            <!– move to left button –>
            <button type=”button” onclick=”move( ‘location_right’, ‘location_left’ )”> < </button>
        </div>

    <!– right select box –>
    <div class=’select_box’>
        <div class=’select_title’>Assigned Locations</div>
        <div style=’clear:both;’></div>
        <select name=’location_right[]’ id=’location_right’ size=’7′ multiple=’multiple’>
        
            <?php       
            $sql = “select
                        l.id as location_id, 
                        l.name as location_name 
                    from 
                        assigned_objects ao, locations l
                    where 
                        ao.type = 2 
                        and ao.object_id in ( {$location_in} )
                        and ao.object_id = l.id”;
            $rs = mysql_query( $sql );
            
            while( $row = mysql_fetch_array( $rs ) ){
                
                echo “<option value=’{$row[‘location_id’]}‘>{$row[‘location_name’]}</option>”;
                
            }
            
            ?>
            
        </select>
    </div>
    
    <div style=’clear:both;’></div>
    <input type=’submit’ value=’Save’ />
        
</form>

<script type=’text/javascript’>

function selectAll( obj_arr ){

    var obj_sel;
    for ( var i = 0; i < obj_arr.length; i++ ){
    
        obj_sel = document.getElementById( obj_arr[i] );
        
        for( var j = 0; j < obj_sel.options.length; j++ ){
            obj_sel.options[j].selected = true;
        }
        
    }
    
}

function move( id_1, id_2 ){
        
        //the box where the value will come from
        var opt_obj = document.getElementById( id_1 );
        
        //the box where the value will be locationd
        var sel_obj = document.getElementById( id_2 );
        
        for ( var i = 0; i < opt_obj.options.length; i++ ){ //loop to check for multiple selections
                
                if ( opt_obj.options[i].selected == true ){ //check if the option was selected
                        
                        //value to be transfered
                        var selected_text = opt_obj.options[i].text;
                        var selected_value = opt_obj.options[i].value;
                        
                        //remove from opt
                        opt_obj.remove( i );
                        
                        //decrease value of i since an option was removed 
                        //therefore the opt_obj.options.length will also decrease
                        i–;
                        
                        //process to sel
                        var new_option_index = sel_obj.options.length;
                        sel_obj.options[new_option_index] = new Option( selected_text, selected_value );
                        
                }
                
        }
}
        
</script>

</body>
</html>

If you have many object types stored in your database, you have to use a loop to generate the pair of select boxes and buttons.

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Thank you for learning from our post about: Move Options Between Two Select Boxes.

Home jQuery

Google Plus Style Notification Box Tutorial

Hi guys! I like the Google+ notification box and lately I wondered how to code a notification box that look like something like that.

I love its simple design and box animation with easing.

So I decided to create my own version.

Today we are going to do a script that will look like the Google+ notification box. I was able to achieve this using jQuery, jQuery easing plugin and PHP.

You should see the live demo before coding:

The database I used (notifications.sql) is included in the code download. Here are the files I used:

  • css/style.css - stylesheet
  • img/ajax-loader.gif - loader image to show while loading the actual notification
  • js/jquery.easing.1.3.js - the plugin used for animation (easing)
  • js/jquery-1.7.1.min.js - our favorite JavaScript library (you can also use the google hosted)
  • config_open_db.php - connect to database
  • index.php - load the notification list and show/hide the box
  • item.php - load the actual notification

index.php code

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<title>Google plus style notification box</title>
		<link rel="stylesheet" type="text/css" href="css/style.css" />
	</head>

<body>

	<div id='bar'>

		<!-- show_notifications when clicked, will show or hide the notification box with fade effect -->
		<div id='show_notifications'>Notifications</div>

		<div style='clear:both;'></div>

		<!-- wrapper is the notification box -->
		<div id="wrapper">

			<!-- div1 will hold the notification list -->
			<div class="full" id="div1">
				<div id='box_header'>
					<div id='noti_text'>Notifications</div>

					<!-- ajax loader was shown when a notification item was clicked -->
					<div id='loader'><img src='img/ajax-loader.gif' /></div>

					<div id='site_link'>
						<a href='https://www.codeofaninja.com/'>+Code of a Ninja</a> &#9658;
					</div>
				</div>

				<div id='noti_list'>
					<?php
					// php code will be here
					?>
				</div>

				<div id='box_footer'>
					<!-- Change link this to your notifications page -->
					<a href='https://www.codeofaninja.com/2012/03/goole-plus-style-notification-box.html?your-link-to-all-notifications/'>View all notifications</a> &#9658;
				</div>
			</div>

			<!-- div2 will hold the actual notification -->
			<div class="full" id="div2">
				<div id='box_header'>
					<div id='noti_text'>&#9668; <a href='#'><span id='back_to_noti'>Back to Notifications</span></a></div>
					<div id='site_link'>
						<a href='https://www.codeofaninja.com/'>+Code of a Ninja</a> &#9658;
					</div>
				</div>

				<div id='actual_notification'>
					<!-- Here is where the actual notification will be loaded -->
				</div>

				<div id='box_footer'>
					<!-- Change link this to your notifications page -->
					<a href='http://yourdomain.com/your-link-to-all-notifications/'>View all notifications</a> &#9658;
				</div>
			</div>


		</div>
	</div>

	<div style='margin-top:20px;'>
		Click the "Notifications" button to show or hide the box.
	</div>

	<div style='margin-top:300px;'>
		<a href='https://www.codeofaninja.com/2012/03/goole-plus-style-notification-box.html'>Tutorial Link Here</a>
	</div>

<!-- javascript code will be here -->

</body>
</html>

PHP Code

Replace "PHP code will be here" line above with the following code.

//this will load the notifications in the database
include 'config_open_db.php';

//selecting record, you can use the limit clause here
//$_GET['owner_id'] is just an example user id passed via url
//you should use session variable here
$sql = "select * from notifications where owner_id = '" . $mysqli->real_escape_string( $_GET['owner_id'] ) . "'";

//query the database
$result = $mysqli->query( $sql );

//count how many records found
$num_results = mysqli_num_rows( $result );

if($num_results>0){ //check if more than 0 record found
	while( $row = $result->fetch_assoc()  ){
		extract($row);

		//display the notification item
		echo "<div class='noti_item'>";

			//noti_id will identify what notification item was clicked
			//which will be used to load the actual notification for the next screen
			echo "<div class='noti_id'>{$id}</div>";
			echo $notification;
		echo "</div>";
	}
}else{
	echo "No notification found.";
}

JavaScript Code

Replace "javascript code will be here" line above with the following code.

<!-- include the jQuery library and jQuery easing plugin -->
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src="js/jquery.easing.1.3.js"></script>

<!-- this script will do the animations and loading actual notificaiton -->
<script type='text/javascript'>
$(window).load(function(){
	//show or hide the notification box
	$('#show_notifications').click(function(){
		$('#wrapper').fadeToggle();
	});

	//prepare/show #div2 on load
	$('#div2').css('left','440px').show();


	$('.noti_item').click(function(){

		//show the loader while waiting for the actual notificaiton to be loaded
		$('#loader').show();
		var noti_id = $(this).find('.noti_id').text();

		//item.php will load the actual notification based on the notification id
		$("#actual_notification").load("item.php?id=" + noti_id, function(){

			//after loading the actual notification,
			//hide the loader when the actual notification was loaded
			$('#loader').hide();

			//animate the box
			//hide #div1 (notification list)
			$('#div1').animate(
				{ left: '-440px' },{
					duration: '350',
					easing: 'easeOutQuint'
			});

			//then show #div2(actual notification)
			$('#div2').animate(
				{ left: 0 }, {
					duration: '350',
					easing: 'easeOutQuint'
			});

		});

	});

	//going back to notification list
	$('#back_to_noti').click(function(){

		//hide #div2 (actual notification)

		$('#div2').animate(
			{ left: '440px' },{
				duration: '350',
				easing: 'easeOutQuint'
		});

		//then show #div1 (notification list)
		$('#div1').animate(
			{ left: 0 }, {
				duration: '350',
				easing: 'easeOutQuint'
		});

		return false;
	});

});

</script>

item.php code

<?php
include 'config_open_db.php';

//selecting record
$sql = "select * from notifications where id = '" . $mysqli->real_escape_string( $_GET['id'] ) . "'";

//query the database
$result = $mysqli->query( $sql );

//count how many records found
$num_results = $result->num_rows;

if($num_results >0){ //check if more than 0 record found
    while( $row = $result->fetch_assoc() ){
        extract($row);
        echo "<div class='noti_indi'>";
            echo "<div class='noti_id'>{$id}</div>";
            echo $notification;
        echo "</div>";
    }
}else{
    echo "No notification found.";
}
?>

CSS code

body{
    font-family:arial;
    font-size:14px;
    padding:0;
    margin:0;
}

#bar{
    background-color:#f1f1f1;
    height:72px;
    border-bottom:thin solid #c0c0c0;
    width:100%;
}

#show_notifications{
    padding:8px;
    border:1px solid #c0c0c0;
    background-color:#fff;
    float:right;
    margin:20px 10px 5px 0;
    cursor:pointer;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    font-weight:bold;
}

#loader{
    float:left;
    margin-left:10px;
    display:none;
}

#wrapper{
    width:440px;
    overflow:hidden;
    position:relative;
    height:300px;
    float:right;
    margin:0 10px 0 0;
    display:none;
}

.full{
    position:absolute;
    width:100%;
}

#div1{
    left:0px;
    padding-bottom:35px;
}

#div2{
    display:none;
    background:#FFFF00;
    left:0px;
    padding-bottom:35px;
}

#box_header{
    height:15px;
    width:418px;
    border:thin solid #c0c0c0;
    line-height:15px;
    background-color:#fff;
    padding:10px;
}

#box_footer{
    height:15px;
    width:418px;
    position:absolute;
    bottom:4px;
    border:thin solid #c0c0c0;
    background-color:#fff;
    padding:10px;
    text-align:center;
    color:#4067C9;
}

#box_footer a{
    color:#4067C9;
    text-decoration:none;
}

#box_footer a:hover{
    text-decoration:underline;
}

#noti_text{
    float:left;
    font-weight:bold;
    color:#4067C9;
}

#noti_text a{
    color:#4067C9;
    text-decoration:none;
}

#noti_text a:hover{
    text-decoration:underline;
}

#site_link{
    float:right;
    color:#4067C9;
}

#site_link a{
    color:#4067C9;
    text-decoration:none;
}

#site_link a:hover{
    text-decoration:underline;
}

.noti_item{
    width:400px;
    height:56px;
    line-height:56px;
    border-bottom:thin solid #c0c0c0;
    border-left:thin solid #c0c0c0;
    padding:10px;
}

.noti_indi{
    width:418px;
    border-bottom:thin solid #c0c0c0;
    padding:10px;
}

.clear{
    clear:both;
}

#noti_list{
    height:232px;
    overflow-y:visible;
    overflow-x:hidden;
    border-right:thin solid #c0c0c0;
    background-color:#F0F0F0;
    cursor:pointer;
}

#actual_notification{
    height:232px;
    overflow-y:visible;
    overflow-x:hidden;
    background-color:#F0F0F0;
    border-left:thin solid #c0c0c0;
    border-right:thin solid #c0c0c0;
}

.noti_id{
    display:none;
}

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Thank you for learning from our post about Google Plus Style Notification Box Tutorial.

Past Month Traffic Details By Google Analytics

Hi guys! Earlier, I (accidentally) checked out our website’s Google Analytics account. I was surprised and happy about what I saw. 
The Stats
For the past month, we got almost 12 thousand unique visitors, more than 14 thousand visits and more than 22 thousand page views. For me these statistics are very encouraging. I realized that I can help other people by writing something about programming. I feel like today, I’m realizing my dream of being a teacher in the future.

Click to enlarge. This link could help us undertand these data.

The Sources

Most of the traffic we got are from search engines, so I thank Google, Bing, Yahoo Search and the like for bringing more people to our website. Second source of traffic are from referral links, so I thank those people who liked, tweeted, shared and linked our posts to Facebook, Twitter, Stackoverflow, DZone, Hacker News and other websites that are linked to our place. Third source of traffic is the direct traffic, thanks for bookmarking, subscribing and returning here guys! 
Click to enlarge.
The New Perspective
Since I’m encouraged and inspired by your positive feedbacks, I will blog more high quality contents (Hmm, maybe as often as every week?) that can be useful for different level of programmers and not just short code snippets or quick tips. I will still reply to your comments depending on my available time. Yes, I’m also aware of negative feedbacks on this site but I prefer to look at it in a positive way. For me, negative feedbacks are great opportunities to learn something. 
Regarding code snippets or quick tips or fast posts, I’d still love to blog about it. I believe they are helpful too. Little code blocks with a little story or experience. I’ll blog these things on a different website or sub domain, something like php.codeofaninja.com, jquery.codeofaninja.com or android.codeofaninja.com. I just want to put more high quality posts as much as possible on our main website codeofaninja.com 
Again, thanks guys! See you!
Home Facebook

Display Facebook Videos To Your Website Script

Update 2: Hi guys! The script on this page is not actively developed anymore, but we have the alternatives!

Learn how to display other Facebook page data using these scripts too!

Hi guys! After my post about displaying Facebook photos and events to website, some of you requested this post – how to display Facebook Fan Page Videos to your website or webpage.

This one is useful if you want your Facebook videos to be shown in your website in a synchronized way.

Once you uploaded a video in your fan page, it will be automatically shown to your website too.

The advantages and risks of this is almost the same with what I discussed in my first post related to this one.

fbvideos

DOWNLOAD CODE LIVE DEMO

On the demo, I just uploaded some random videos of mine, taken using my Android phone. Haha!

In this post I’ll show you the code on:

  • How to pull videos from you Facebook Page and display it to your website.
  • We will retrieve just the video’s title, date it was created, the actual video and its description.

We were able to achieve this using the FQL, Facebook PHP SDK. As of this posting, the current PHP SDK version I downloaded is v.3.1.1. And of course, creating a Facebook App so you can have your own AppId and App Secret Id.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja Dummy Page Videos</title>
        <style type=’text/css’>
            #page_title{
                font-size:16px;
                font-weight:bold;
                margin: 0 0 10px 0;
            }
           
            .date_created{
                font:italic 12px Arial, Helvetica, sans-serif;
                color:#fff;
                margin:0 0 5px 0;
            }
           
            .video_desc{
                font:12px Arial, Helvetica, sans-serif;
                color:#fff;
                margin:0 0 5px 0;
            }
           
            .video_item{
                width:320px; /*i tried it with a bigger video and it’s 400px*/
                float:left;
                padding:5px;
                background-color:brown;
                margin: 5px;
            }
           
            .video_title{
                font:20px Arial, Helvetica, sans-serif;
                font-weight:bold;
                color:#fff;
            }
        </style>
    </head>
<body>
<div class=’page_title’>
    These videos are synchronized with this
    <a href=’https://www.facebook.com/video/?id=221167777906963′ target=’_blank’>
        Dummy Page Videos
    </a>
</div>
<?php
require ‘fb-sdk/src/facebook.php’;

//specify you appId and secret
$facebook = new Facebook(array(
  ‘appId’  => ‘change_to_your_app_id’,
  ‘secret’ => ‘change_to_your_app_secret’,
  ‘cookie’ => true, // enable optional cookie support
));

//query to get videos
//specify you fan page id, I got 221167777906963
//you can also use the LIMIT clause here if you want to show limited number of videos only
$fql = “SELECT
            vid, owner, title, description, thumbnail_link,
            embed_html, updated_time, created_time
        FROM
            video
        WHERE owner=221167777906963″;
           
$param  =   array(
 ‘method’    => ‘fql.query’,
 ‘query’     => $fql,
 ‘callback’  => ”
);
$fqlResult   =   $facebook->api($param);

//loop through each videos
foreach( $fqlResult as $keys => $values ){
   
    echo “<div class=’video_item’>”;
        echo “<div class=’video_title’>” . $values['title'] . “</div>”;
        echo “<div class=’date_created’>Date Created: “ . date( ‘l, F d, Y’, $values['created_time'] ) . “</div>”;
        echo $values['embed_html'];
        echo “<div class=’video_desc’>” . $values['description'] . “</div>”;
    echo “</div>”;
}
?>
   
  </body>
</html>

You can also retrieve other videos information if you want, please see the videos table of Facebook.