Jump to content

Instagram API Pagination


Caiken

Recommended Posts

I am trying to use Cosenary's Instagram Class which is located at..
https://github.com/cosenary/Instagram-PHP-API

Specifically, I am trying to do Pagination with a Tag Search. I want it to loop the process until it reach's yesterday's posts. I will run this script daily.
 

              <?php

            /**
            * Instagram PHP API
            *
            * @link https://github.com/cosenary/Instagram-PHP-API
            * @author Christian Metz
            * @since 01.10.2013
            */

            require '../dbinclude.php';

            require 'Instagram.php';
            use MetzWeb\Instagram\Instagram;

            // initialize class
            $instagram = new Instagram(array(
            'apiKey'      => '***************',
            'apiSecret'   => '***************',
            'apiCallback' =>  '*************' // must point to success.php
            ));

            ?>

            <?php
            $i = 0;
            $imagecount = 0;
            do {
            $i++;
            echo "Pagination restart";      
            $photos = $instagram->getTagMedia('kittens');
            $result = $instagram->pagination($photos);


            foreach($result->data as $post) {
            $image =  mysqli_real_escape_string($toolconn, $post->images->low_resolution->url);
            $caption =  mysqli_real_escape_string($toolconn, $post->caption->text);
            $author =  mysqli_real_escape_string($toolconn, $post->user->username);
            $created =  mysqli_real_escape_string($toolconn, $post->created_time);   
            $created = date("Y-m-d H:i:s", $created);
            $compare = substr($created, 0, 10);
            $twodays = date("Y-m-d",strtotime("-2 days"));
            $link = $post->link;
            //                        
            echo $twodays . "<br>";
            echo $compare . "<Br>";
            $sql = "INSERT INTO userfeeds (link, thumbnail, created_at, caption, author)
            VALUES ('$link', '$image', '$created', '$caption', '$author')";
            // $exec = mysqli_query($toolconn, $sql);

            echo $sql . "<br>";

            echo "Created; " . $compare . "<BR>";
            echo "Comparison; " . $twodays . "</br><hr>";

            }

            } while ($compare != $twodays);
            ?>


I have been trying to do this for about three weeks now. For some reason, my loop doesnt work. Help!


In the documentation it says the following..
 

                 Each endpoint has a maximum range of results, so increasing the limit parameter above the limit won't help (e.g. getUserMedia() has a limit of 90).

            That's the point where the "pagination" feature comes into play. Simply pass an object into the pagination() method and receive your next dataset:

            <?php
                $photos = $instagram->getTagMedia('kitten');

                $result = $instagram->pagination($photos);
            ?>

            Iteration with do-while loop.

Basically my end goal is to make sure everyday I didnt miss a post.. I have been trying to work on this for literally three weeks and I have gotten nowhere :(
 

Link to comment
https://forums.phpfreaks.com/topic/292878-instagram-api-pagination/
Share on other sites

Since nobody ever replied to this will try to help a little.

 

Specifically, I am trying to do Pagination with a Tag Search.

 

You don't want to change the class, instead you want to use your already scraped data with a search and pagination.

 

I want it to loop the process until it reach's yesterday's posts

 

What if was more than 90 results for that specific search term?

If instagram api has a from startrow or a way to query by date can take advantage of that

 

From what I see is a max 90 results anything you searched for, such as your kitten

The $i variable is used as a count but not really doing anything.

It could potentially be used as a pagination on just the results got back from the live api, but in this instance you are saving them all to a database so is worthless.

 

You can call to the script using single GET requests...coming from an array or lists you create somehow

 

and here is a way can do that

//add whatever want to the array
$fetch_terms = array("kitten","dog","cat","funny","animal","penguin","horse","donkey");
shuffle($fetch_terms);//randomize it
if(isset($_GET['fetch']) && trim($_GET['fetch']) != ''){
$fetch_term = trim($_GET['fetch']);
} else {
$fetch_term = $fetch_terms[0];
}

then edit this line to

$photos = $instagram->getTagMedia($fetch_term);

now if call to the script with something like mysite.com/instagram.php?fetch=kitten it will retrieve kitten results

if don't use the fetch query parameter in the url it would use a random one from the $fetch_terms array

 

to handle ensuring getting them all, well unless you can query instagram a certain date, will just get latest ones, I never personally looked at their api

but you could just run it as often as like, and set unique constraints in your database on 1 or more columns to ensure duplicates are not added

 

$link = $post->link; looks like a good item to make it unique

the command to do this for mysql

ALTER TABLE userfeeds ADD UNIQUE (link);
I will run this script daily.

 

Unless you wanted just kittens,you need to run this many times a day on every fetch term you used in the script.

 

$caption data could be used for your search later on, but you could also make a new column and use the $fetch_term you specify as a category/tag system

This way is no need to search but instead can make the categories and a click will get you all those results...or have both.

 

A combination search and pagination is very possible once you have the data stored mysql.

 

Make a simple search form

 

I suggest looking at this old mysql_ function pagination tutorial

 

Mac_Gyver was so nice as to make a combo mysql/mysqli one

http://forums.phpfreaks.com/topic/291074-php-mysli-pagination-with-items-per-page-select-option/?do=findComment&comment=1491152

 

Depending what you do with categories or can use fulltext search (which takes a bit of work,such creating an index in mysql) or do a LIKE in the sql query

 

Since people do not do single words all the time, you would need to explode them by spaces

For fulltext is a few different types of advanced searches and operators, take a look at boolean mode

 

Example fulltext in boolean mode

$sql = "SELECT * FROM userfeeds WHERE MATCH (caption) AGAINST ('$search_term' IN BOOLEAN MODE) Limit $offset, $rowsperpage";

Example LIKE sql

$sql = "SELECT * FROM userfeeds WHERE caption LIKE '%$search_term%' LIMIT $offset, $rowsperpage";

The count sql also needs to be modified..minus the limit with offset and rows per page

$sql = "SELECT COUNT(*) FROM userfeeds WHERE caption LIKE '%$search_term%'";

Now that's all fine for the search aspect and pagination, but should also make multiple sql queries if nothing was searched for so can do all results

$search_term needs to exploded by spaces if multiple words, LIKE needs multiple where/and/or clauses while fulltext are spaced or use the + operator or others

 

Untested code using my search integrated into mac_gyvers pagination with some changes

<?php
//configuration

define('SOURCE','mysqli'); // the method/type of data source - mysql, mysqli

//database
$db_server = "localhost";//sever name, usually localhost
$db_user = "username";//mysql username
$db_pass = "password";//mysql password
$db_database "database_name";//mysql database
$tablename = "userfeeds"; //set table name for query
$column = "caption"; //set column name for query
$fulltext_search = false; //like or fulltext ...determine what type of search method, fulltext requires creating an index
//end configuration

$search_query = '';//leave blank

switch(SOURCE){
        case 'mysql':
            // database connection info
            $conn = mysql_connect($db_server,$db_user,$db_pass) or trigger_error("SQL", E_USER_ERROR);
            $db = mysql_select_db($db_database,$conn) or trigger_error("SQL", E_USER_ERROR);
		break;
		
		case 'mysqli':
            // database connection info
            $conn = mysqli_connect($db_server,$db_user,$db_pass,$db_database) or trigger_error("SQL", E_USER_ERROR);
		break;
}		

if(isset($_GET['search']) && trim($_GET['search']) != ''){

$explode_search = array();
$search = trim($_GET['search']);
$search = preg_replace('/\s+/', ' ', $search);
$explode_search = explode(" ",$search);

if($fulltext_search == true){
$trimmed_words = '';
foreach ($explode_search as $trim_words) {
        if (substr($trim_words, 0, 1) != "-" || substr($trim_words, 0, 1) != '"') {
            $trim_words = trim($trim_words);
            $trimmed_words .= " +$trim_words";
        } else {
            $trim_words = trim($trim_words);
            $trimmed_words .= " $trim_words";
        }
}//end loop
$trimmed_words = trim($trimmed_words);
$trimmed_words = preg_replace('/\s+/', ' ', $trimmed_words);

case 'mysql':
$trimmed_words = mysql_real_escape_string($trimmed_words);
break;

case 'mysqli':
$trimmed_words = mysqli_real_escape_string($conn, $trimmed_words);
break;

}

//assembled search query
$search_query .= "WHERE MATCH ($column) AGAINST ('$trimmed_words' IN BOOLEAN MODE)) ";

} else {

$multiple_like = array();
foreach($explode_search as $search_word){
switch(SOURCE){
case 'mysql':
$search_word = mysql_real_escape_string($search_word);
break;

case 'mysqli':
$search_word = mysqli_real_escape_string($conn, $search_word);
break;

}

$multiple_like[] = "`$column` LIKE '%" . $search_word . "%' ";
}//end loop


if(count($multiple_like) > 0 ){
//assembled search query
   $search_query .= "WHERE " . implode (' AND ', $multiple_like);
}

}//end fulltext if


}//end GET search

   
    switch(SOURCE){
        case 'mysql':           
			// find out how many rows are in the table 
            $sql = "SELECT COUNT(*) FROM $tablename $search_query";
            $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
            $r = mysql_fetch_row($result);
            $numrows = $r[0];
        break;
     
        case 'mysqli':    
            // find out how many rows are in the table 
            $sql = "SELECT COUNT(*) FROM $tablename $search_query";
            $result = mysqli_query($conn,$sql) or trigger_error("SQL", E_USER_ERROR);
            $r = mysqli_fetch_row($result);
            $numrows = $r[0];
        break;
    }
     
     
    // number of rows to show per page
    $rowsperpage = 10; // (default value when using dynamic rows per page)
     
     
    // dynamic rows per page, handling and form
    $per_page = array(1,5,10,25,50); // choices for select/option menu. also used to limit (min, max) the submitted value
     
    $rowsperpage = isset($_GET['perpage']) ? (int)$_GET['perpage'] : $rowsperpage; // get submitted value or the default
     
    $rowsperpage = max(min($per_page),$rowsperpage); // limit to the minimum value
    $rowsperpage = min(max($per_page),$rowsperpage); // limit to the maximum value
     
    // produce rows per page form
    $rpp_form = "<form method='get' action=''>\n<select name='perpage' onchange='this.form.submit();'>\n";
    foreach($per_page as $item){
        $sel = $rowsperpage == $item ? 'selected' : '';
        $rpp_form .= "<option value='$item' $sel>$item</option>\n";
    }
    $rpp_form .= "</select>\n<noscript><input type='submit'></noscript>\n</form>\n";
     
     
    // find out total pages
    $totalpages = ceil($numrows / $rowsperpage);
     
    // get the current page or set a default
    if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
       // cast var as int
       $currentpage = (int) $_GET['currentpage'];
    } else {
       // default page num
       $currentpage = 1;
    } // end if
     
    // if current page is greater than total pages...
    if ($currentpage > $totalpages) {
       // set current page to last page
       $currentpage = $totalpages;
    } // end if
    // if current page is less than first page...
    if ($currentpage < 1) {
       // set current page to first page
       $currentpage = 1;
    } // end if
     
    // the offset of the list, based on current page 
    $offset = ($currentpage - 1) * $rowsperpage;
     
    switch(SOURCE){
        case 'mysql':
            // get the info from the db 
            $sql = "SELECT * FROM $tablename $search_query LIMIT $offset, $rowsperpage";
            $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
            $rows = array();
            while ($row = mysql_fetch_assoc($result)) {
                $rows[] = $row;
            } // end while
        break;
     
        case 'mysqli':
            // get the info from the db 
            $sql = "SELECT * FROM $tablename $search_query LIMIT $offset, $rowsperpage";
            $result = mysqli_query($conn,$sql) or trigger_error("SQL", E_USER_ERROR);
            $rows = array();
            while ($row = mysqli_fetch_assoc($result)) {
                $rows[] = $row;
            } // end while
        break;
    }
     
    // while there are rows to be fetched...
    foreach($rows as $row) {
       // echo data
       echo $row['id'] . " : " . $row['number'] . "<br />";
    } // end foreach
     
     
    // display dynamic rows per page form
    echo $rpp_form;
     
     
    /******  build the pagination links ******/
    // range of num links to show
    $range = 3;
     
    // if not on page 1, don't show back links
    if ($currentpage > 1) {
       // show << link to go back to page 1
       $_GET['currentpage'] = 1;
       $qs = http_build_query($_GET, '', '&');
       echo " <a href='{$_SERVER['PHP_SELF']}?$qs'><<</a> ";
       // get previous page num
       $prevpage = $currentpage - 1;
       // show < link to go back to 1 page
       $_GET['currentpage'] = $prevpage;
       $qs = http_build_query($_GET, '', '&');  
       echo " <a href='{$_SERVER['PHP_SELF']}?$qs'><</a> ";
    } // end if 
     
    // loop to show links to range of pages around current page
    for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
       // if it's a valid page number...
       if (($x > 0) && ($x <= $totalpages)) {
          // if we're on current page...
          if ($x == $currentpage) {
             // 'highlight' it but don't make a link
             echo " [<b>$x</b>] ";
          // if not current page...
          } else {
             // make it a link
            $_GET['currentpage'] = $x;
            $qs = http_build_query($_GET, '', '&');
             echo " <a href='{$_SERVER['PHP_SELF']}?$qs'>$x</a> ";
          } // end else
       } // end if 
    } // end for
                     
    // if not on last page, show forward and last page links        
    if ($currentpage != $totalpages) {
       // get next page
       $nextpage = $currentpage + 1;
        // echo forward link for next page
       $_GET['currentpage'] = $nextpage;
       $qs = http_build_query($_GET, '', '&');
       echo " <a href='{$_SERVER['PHP_SELF']}?$qs'>></a> ";
       // echo forward link for lastpage
       $_GET['currentpage'] = $totalpages;
       $qs = http_build_query($_GET, '', '&');
       echo " <a href='{$_SERVER['PHP_SELF']}?$qs'>>></a> ";
    } // end if
    /****** end build pagination links ******/
?>

Maybe I'll figure out a way to handle the case for mysql and mysqli better a day and also add pdo to this.

Didn't have time to fuss with it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.