<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
><channel><title>Xavisys&#187; pagination</title> <atom:link href="http://xavisys.com/tag/pagination/feed/" rel="self" type="application/rss+xml" /><link>http://xavisys.com</link> <description>WordPress Plugins and Custom WordPress Development</description> <lastBuildDate>Thu, 15 Jul 2010 17:58:50 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.0.1</generator> <atom:link rel='hub' href='http://xavisys.com/?pushpress=hub'/> <item><title>PHP Pagination with mysqli</title><link>http://xavisys.com/php-pagination-with-mysqli/</link> <comments>http://xavisys.com/php-pagination-with-mysqli/#comments</comments> <pubDate>Fri, 15 Jun 2007 16:46:52 +0000</pubDate> <dc:creator>Aaron D. Campbell</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[mysqli]]></category> <category><![CDATA[pagination]]></category><guid
isPermaLink="false">http://xavisys.com/php-pagination-with-mysqli/</guid> <description><![CDATA[I&#8217;m asked pretty regularly for help with pagination in PHP. I have a nice mysqli pagination class that I use. Once it&#8217;s implemented, it is used like this: /** * $db is your mysqli connection * $query is your query * 'mailPage' is the $_GET variable to use for the pages. It defaults to 'page' [...]]]></description> <content:encoded><![CDATA[<p>I&#8217;m asked pretty regularly for help with pagination in PHP.  I have a nice mysqli pagination class that I use.  Once it&#8217;s implemented, it is used like this:</p><pre class="brush: php;">
/**
* $db is your mysqli connection
* $query is your query
* 'mailPage' is the $_GET variable to use for the pages.  It defaults to 'page' but using different values lets you have separate
* paginated data on that same web page.  Setting multiple paginated items on the same webpage to the same &quot;page&quot; variable
* will mean that when one goes to page two, all of them go to page 2.
*/
// Require the class
require_once('paginate.class.php');
// Lets not use your normal SELECT * FROM table query...just to show it still works
$query = &lt;&lt;&lt;
    SELECT
        `mail`.`id`,
        `mail2`.`read`,
        `mail2`.`seen`,
        `mail`.`from`,
        `mail`.`sent`,
        `mail`.`subject`,
        `mail`.`body`,
        `users`.`full_name` as from_name
    FROM `mail`
    JOIN `users`
        ON (`mail`.`from` = `users`.`id`)
    JOIN `mail2`
        ON (`mail`.`id` = `mail2`.`mess_id`)
    WHERE
        `mail2`.`uid`=1 &amp;&amp;
        `mail2`.`folder`=1
    ORDER BY
        `mail`.`sent` DESC
EOQ;

// Create our paginate object, and pass it the database, query, and page var
$paginate = new Paginate($db, $query, 'mailPage');
// Run the query
$r = $paginate-&gt;get_results();

// Loop through our results
while ($message = $r-&gt;fetch_object()) {
// Create your page of information
}

// Show the page links
echo $paginate-&gt;show_pages();
</pre><p><span
id="more-36"></span></p><p>Now for the actual code of the class:</p><pre class="brush: php;">
&lt;?php
/**
 * paginate.class.php - PHP 5 class for pagination of mysqli results
 *
 * @author    Aaron D. Campbell &lt;aronCampbell@ezdispatch.com&gt;
 *
 * @version 1.0.4
 *
 * Changes:
 * 1.0.4:
 *   Added urlencoding to each get value when generating the links
 * 1.0.3:
 *   Added show_result_text() which displays a string like this: Showing __-__ of ___ total
 *   Changed show_pages() to return only the links without the containing div
 * 1.0.2:
 *   Added the ability to specify what $_GET variable is used to track the current page (allows for multiple instances on one webpage)
 *   Added &quot;first&quot; and &quot;last&quot; links to the page links
 * 1.0.1:
 *   Implemented more strict error checking on the page variable
 *   Changed PHP_SELF variables into SCRIPT_NAME to avoid vulnerabilities ( http://blog.phpdoc.info/archives/13-guid.html )
 * 1.0.0: original version
 */
class Paginate {
    //mysqli connection resource
    private $db;
    //MySQL query
    private $q;
    //number of rows per page.(default to 20)
    private $per_page = 20;
    //$_GET index to use for tracking page number
    private $page_var = 'page';
    //number of rows returned by the query.
    private $total_rows;
    //total number of pages.
    private $total_pages;
    //number of page links to show on either side of the current page.
    private $links_each_side = 3;
    //maximum number of pages to just show all, before using ellipses
    private $max_show_all = 10;

    /**
     * Set everything up.
     *
     * @param mysqli_resource    $db - mysqli connection resource
     * @param string $q - MySQL query
     * @param string[optional] $page_var - $_GET/$_SESSION['paginate_class'] index to use for &quot;Current Page&quot; defaults to 'page'
     *
     * @return void
     */
    public function __construct($db, $q, $page_var='page') {
        $this-&gt;db = $db;
        $this-&gt;q = $q;
        $this-&gt;page_var = $page_var;
        $this-&gt;check_page_var();
    }

    /**
     * Make sure that the current page is valid (whole number &gt;= 1)
     */
    public function check_page_var() {
        /*
        * if no page is specified, set it to 1.  If it IS specified, force it to int, and make sure
        * it is &gt;= 1
        */
        if (isset($_GET[$this-&gt;page_var]) &amp;&amp; (int)$_GET[$this-&gt;page_var] &gt; 0) {
            $_SESSION['paginate_class'][$this-&gt;page_var] = (int)$_GET[$this-&gt;page_var];
        } elseif (!isset($_SESSION['paginate_class'][$this-&gt;page_var])) {
            $_SESSION['paginate_class'][$this-&gt;page_var] = 1;
        }

        if ($this-&gt;per_page != 0) {
            $this-&gt;create_query();
        }
    }

    /**
     * Set the number of results returned per page.
     *
     * @param Unsigned Int $per_page
     */
    public function set_per_page($per_page) {
        $this-&gt;per_page = abs((int) $per_page);
    }

    /**
     * Set the number of page links to show on either side of the current page.
     *
     * @param Unsigned Int $links_each_side
     */
    public function set_links_each_side($links_each_side) {
        $this-&gt;links_each_side = abs((int) $links_each_side);
    }

    /**
     * Set maximum number of pages to just show all, before using ellipses
     * 0 will show all no matter what
     *
     * @param Unsigned Int $max_show_all
     */
    public function set_max_show_all($max_show_all) {
        $this-&gt;max_show_all = abs((int) $max_show_all);
    }

    /**
     * Used to get the result set, and set the Total rows.
     *
     * @return mysqli result object
     */
    public function get_results() {
        $return = $this-&gt;db-&gt;query($this-&gt;q);
        //get the number of rows that WOULD have been returned if there was no LIMIT
        //This is done by using FOUND_ROWS() after using SQL_CALC_FOUND_ROWS in the query
        $this-&gt;total_rows = array_pop($this-&gt;db-&gt;query('SELECT FOUND_ROWS()')-&gt;fetch_row());
        return $return;
    }

    /**
     * Show current results being viewed and total
     *
     * @return string - Showing __-__ of ___ total
     */
    public function show_result_text() {
        $start =<sup><a href="http://xavisys.com/php-pagination-with-mysqli/#footnote_0_36" id="identifier_0_36" class="footnote-link footnote-identifier-link" title="$_SESSION['paginate_class'][$this-&amp;gt;page_var]-1) * $this-&amp;gt;per_page)+1;
        $end = (($start-1+$this-&amp;gt;per_page) &amp;gt;= $this-&amp;gt;total_rows)? $this-&amp;gt;total_rows:($start-1+$this-&amp;gt;per_page);
        return &amp;quot;Showing {$start}-{$end} of {$this-&amp;gt;total_rows} total&amp;quot;;
    }

    /**
     * Creates links to other pages.
     *
     * @return string - page links
     */
    public function show_pages() {
        //If number of rows per page is 0 (unlimited), return an empty string.
        if ($this-&amp;gt;per_page == 0) {
            return '';
        }
        /*
        * If the user did not run get_results, we run it.  We could modify the query
        * to remove the SQL_CALC_FOUND_ROWS, and the limit...and either make it into
        * a count() query, or check num_rows...but it's a lot easier to just call
        * get_results with the query as it is.
        */
        if (!isset($this-&amp;gt;total_rows">1</a></sup> {
            $this-&gt;get_results();
        }
        //calculate the number of pages.
        $this-&gt;total_pages = ceil($this-&gt;total_rows/$this-&gt;per_page);

        //we use this array to store the page links that we want...so we can implode on |
        $page_array = array();

        $first = $this-&gt;get_page_link(1, '&amp;lt;&amp;lt; First');
        $last = ($this-&gt;total_pages &gt; 1)? $this-&gt;total_pages:1;
        $last = $this-&gt;get_page_link($last, 'Last &amp;gt;&amp;gt;');

        //if the number of pages is not more than the max that was specified, add
        //all the pages.
        if ($this-&gt;total_pages &lt;= $this-&gt;max_show_all || $this-&gt;max_show_all == 0) {
            for ($i=1; $i&lt;=$this-&gt;total_pages; $i++) {
                $page_array[] = $this-&gt;get_page_link($i);
            }
        } else {
            /*
            * make sure that page one gets in...but only if it wouldn't make it on
            * it's own...we don't want it there twice.
            */
            if($_SESSION['paginate_class'][$this-&gt;page_var] &gt;= $this-&gt;links_each_side+2) {
                $page_array[] = $this-&gt;get_page_link(1);
            }
            // If needed, add an ellipsis after page one.
            if($_SESSION['paginate_class'][$this-&gt;page_var] &gt;= $this-&gt;links_each_side+3) {
                $page_array[] = '...';
            }
            //Set the first page to be added (for pages in the main group)
            if ($_SESSION['paginate_class'][$this-&gt;page_var]-$this-&gt;links_each_side &lt;= 1) {
                $start = 1;
            } elseif ($_SESSION['paginate_class'][$this-&gt;page_var] &gt; $this-&gt;total_pages-$this-&gt;links_each_side) {
                $start = $this-&gt;total_pages-(2*$this-&gt;links_each_side);
            } else {
                $start = $_SESSION['paginate_class'][$this-&gt;page_var]-$this-&gt;links_each_side;
            }
            //Set the last page to be added (for pages in the main group)
            if ($_SESSION['paginate_class'][$this-&gt;page_var]+$this-&gt;links_each_side &gt;= $this-&gt;total_pages) {
                $end = $this-&gt;total_pages;
            } elseif ($_SESSION['paginate_class'][$this-&gt;page_var] &lt; $this-&gt;links_each_side+1) {
                $end = (2*$this-&gt;links_each_side)+1;
            } else {
                $end = $_SESSION['paginate_class'][$this-&gt;page_var]+$this-&gt;links_each_side;
            }
            //add the pages for the main group.
            for ($i=$start; $i&lt;=$end; $i++) {
                $page_array[] = $this-&gt;get_page_link($i);
            }
            // If needed, add an ellipsis before the last page.
            if($_SESSION['paginate_class'][$this-&gt;page_var] &lt;= $this-&gt;total_pages-$this-&gt;links_each_side-2) {
                $page_array[] = '...';
            }
            /*
            * make sure that the last page gets in...but only if it wouldn't make it
            * on it's own...we don't want it there twice.
            */
            if($_SESSION['paginate_class'][$this-&gt;page_var] &lt;= $this-&gt;total_pages-$this-&gt;links_each_side-1) {
                $page_array[] = $this-&gt;get_page_link($this-&gt;total_pages);
            }
        }
        //implode the links and ellipses into a | seperated string, and center in a div
        return &quot;{$first}&amp;nbsp;&amp;nbsp;&amp;nbsp;&quot;.implode(' | ',$page_array).&quot;&amp;nbsp;&amp;nbsp;&amp;nbsp;{$last}&quot;;
    }

    /**
     * Creates a page link, including the current $_GET string...updating only
     * $_SESSION['paginate_class'][$this-&gt;page_var].  It also returns only text (no link) if $p is the current
     * page.
     *
     * @param int $p - Page number to create link for
     * @return string - Link
     */
    private function get_page_link($p, $text=NULL) {
        if ($text === NULL) {
            $text = $p;
        }
        if ($p != $_SESSION['paginate_class'][$this-&gt;page_var]) {
            $_GET[$this-&gt;page_var] = $p;
            $get_string = array();
            foreach ($_GET as $k=&gt;$v) {
                if (is_array($v)) {
                    foreach ($v as $cur_v) {
                        $cur_v = urlencode($cur_v);
                        $get_string[] = &quot;{$k}[]={$cur_v}&quot;;
                    }
                } else {
                    $v = urlencode($v);
                    $get_string[] = &quot;{$k}={$v}&quot;;
                }
            }
            $get_string = implode('&amp;amp;',$get_string);
            return &quot;&lt;a href=\&quot;{$_SERVER['SCRIPT_NAME']}?{$get_string}\&quot;&gt;{$text}&lt;/a&gt;&quot;;
        } else {
            return $text;
        }
    }

    /**
     * Adds the proper LIMIT to the query, as well as adding SQL_CALC_FOUND_ROWS
     * which is used to get the total number of rows (ignoring LIMIT) without
     * doing a count() query
     */
    private function create_query() {
        //calculate the starting row
        $start = ($_SESSION['paginate_class'][$this-&gt;page_var]-1) * $this-&gt;per_page;
        //insert SQL_CALC_FOUND_ROWS and add the LIMIT
        $this-&gt;q = preg_replace('/^SELECT\s/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this-&gt;q).&quot; LIMIT {$start},{$this-&gt;per_page}&quot;;
    }
}
?&gt;</pre><h3 class='related_post_title'>Related Posts:</h3><ul
class='related_post'><li><a
href='http://xavisys.com/howto-create-stream-csv-php/' title='Howto: Create and Stream a CSV with PHP'>Howto: Create and Stream a CSV with PHP</a></li><li><a
href='http://xavisys.com/wordpress-25-shortcodes/' title='WordPress 2.5 Shortcodes'>WordPress 2.5 Shortcodes</a></li><li><a
href='http://xavisys.com/wordpress-should-update-get_sidebar-to-work-with-multiple-sidebars/' title='Wordpress Should Update get_sidebar to Work With Multiple Sidebars'>WordPress Should Update get_sidebar to Work With Multiple Sidebars</a></li><li><a
href='http://xavisys.com/php-function-to-redirect-a-user-with-a-message/' title='PHP function to Redirect a user with a message'>PHP function to Redirect a user with a message</a></li><li><a
href='http://xavisys.com/replace-every-other-occurrence-with-str_replace/' title='Replace every other occurrence with str_replace'>Replace every other occurrence with str_replace</a></li></ul><ol
class="footnotes"><li
id="footnote_0_36" class="footnote">$_SESSION['paginate_class'][$this-&gt;page_var]-1) * $this-&gt;per_page)+1;
$end = (($start-1+$this-&gt;per_page) &gt;= $this-&gt;total_rows)? $this-&gt;total_rows:($start-1+$this-&gt;per_page);
return &quot;Showing {$start}-{$end} of {$this-&gt;total_rows} total&quot;;
}/**
* Creates links to other pages.
*
* @return string - page links
*/
public function show_pages() {
//If number of rows per page is 0 (unlimited), return an empty string.
if ($this-&gt;per_page == 0) {
return '';
}
/*
* If the user did not run get_results, we run it.  We could modify the query
* to remove the SQL_CALC_FOUND_ROWS, and the limit...and either make it into
* a count() query, or check num_rows...but it's a lot easier to just call
* get_results with the query as it is.
*/
if (!isset($this-&gt;total_rows</li></ol>]]></content:encoded> <wfw:commentRss>http://xavisys.com/php-pagination-with-mysqli/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (user agent is rejected)
Database Caching using apc
Content Delivery Network via cdn.xavisys.com

Served from: xavisys.com @ 2010-09-07 00:41:25 -->