I've spent a couple of hours trying to figure this out.

I found a tutorial http://www.php-mysql-tutorial.com/php-mysql-paging.php that is really close to what I want except it doesn't stop creating numbers. For instance if I have 300 pages then it would do this.

1 2 3 4 5 6 7 ... 300

I want to have it so if the user is on the first page then it will echo out the next 9 numbers.
Example:

1 2 3 4 5 6 7 8 9 10 Next

Or if they're on page 15 it will echo out the previous 5 numbers and the next 5 numbers.
Example:
Prev 10 11 12 13 14 15 16 17 18 19 20 Next

and last if they're on the last page it would look like this

Prev 290 291 292 293 294 295 296 297 298 299 300

Please don't send me to google. I've googled "php paging like google" "pagination like google with php" and every other way I can think of.

Thanks in advance!

    perhaps a little raw for you - but this is what i use in dozen of places to do that

    
    if ($numofpages > '1' ) {
    
    
    		$range =10;
    		$range_min = ($range % 2 == 0) ? ($range / 2) - 1 : ($range - 1) / 2;
    		$range_max = ($range % 2 == 0) ? $range_min + 1 : $range_min;
    		$page_min = $this->page_num- $range_min;
    		$page_max = $this->page_num+ $range_max;
    
    		$page_min = ($page_min < 1) ? 1 : $page_min;
    		$page_max = ($page_max < ($page_min + $range - 1)) ? $page_min + $range - 1 : $page_max;
    		if ($page_max > $numofpages) {
    			$page_min = ($page_min > 1) ? $numofpages - $range + 1 : 1;
    			$page_max = $numofpages;
    		}
    
    		$page_min = ($page_min < 1) ? 1 : $page_min;
    
    		//$page_content .= '<p class="menuPage">';
    
    		if ( ($this->page_num > ($range - $range_min)) && ($numofpages > $range) ) {
    			$page_pagination .= '<a class="num"  title="First" href="'.$_SERVER['REDIRECT_URL'].'/?page=1">&lt;</a> ';
    		}
    
    		if ($this->page_num != 1) {
    			$page_pagination .= '<a class="num" href="'.$_SERVER['REDIRECT_URL'].'?/page='.($this->page_num-1). '">Previous</a> ';
    		}
    
    		for ($i = $page_min;$i <= $page_max;$i++) {
    			if ($i == $this->page_num)
    			$page_pagination .= '<span class="num"><strong>' . $i . '</strong></span> ';
    			else
    			$page_pagination.= '<a class="num" href="'.$_SERVER['REDIRECT_URL'].'/?page='.$i. '">'.$i.'</a> ';
    		}
    
    		if ($this->page_num < $numofpages) {
    			$page_pagination.= ' <a class="num" href="'.$_SERVER['REDIRECT_URL'].'/?page='.($this->page_num + 1) . '">Next</a>';
    		}
    
    
    		if (($this->page_num< ($numofpages - $range_max)) && ($numofpages > $range)) {
    			$page_pagination .= ' <a class="num" title="Last" href="'.$_SERVER['REDIRECT_URL'].'/?page='.$numofpages. '">&gt;</a> ';
    		}
    		$page['PAGINATION'] ='<p id="pagination">'.$page_pagination.'</p>';
    	}//end if more than 1 page
    
    

      Dagon - Thanks SO much. I had to change the $this->page_num to just a variable like this $page_num, but other than that it works perfectly!

      If anyone wants this code here it is.

      <?php
      // how many rows to show per page
      $rowsPerPage = "10";
      
      // by default we show first page
      $page_num = 1;
      
      // if $_GET['page'] defined, use it as page number
      if(isset($_GET['page']))
      {
          $page_num = $_GET['page'];
      }
      
      // Zero is an incorrect page
      // So we switch the zero with 1
      // Mainly because it will cause an error with the SQL
      if($page_num == "0") {
      	$page_num = "1";
      }
      
      // counting the offset
      $sql = "SELECT * FROM table LIMIT $offset, $rowsPerPage";
      $res = mysql_query($sql) or die(mysql_error());
      
      
      // print the random numbers
      while($row = mysql_fetch_array($res))
      {
      //Echo out your table contents here.
      }
      
      // how many rows we have in database
      $sql2   = "SELECT COUNT(*) AS numrows FROM table";
      $res2  = mysql_query($sql2) or die(mysql_error());
      
      $row2     = mysql_fetch_array($res2 MYSQL_ASSOC);
      $numrows = $row2['numrows'];
      
      // how many pages we have when using paging?
      $numofpages = ceil($numrows/$rowsPerPage);
      
      // print the link to access each page
      $self = "/Sermons?series=" . $series;
      
      if ($numofpages > '1' ) {
      
      
              $range =10;
              $range_min = ($range % 2 == 0) ? ($range / 2) - 1 : ($range - 1) / 2;
              $range_max = ($range % 2 == 0) ? $range_min + 1 : $range_min;
              $page_min = $page_num- $range_min;
              $page_max = $page_num+ $range_max;
      
              $page_min = ($page_min < 1) ? 1 : $page_min;
              $page_max = ($page_max < ($page_min + $range - 1)) ? $page_min + $range - 1 : $page_max;
              if ($page_max > $numofpages) {
                  $page_min = ($page_min > 1) ? $numofpages - $range + 1 : 1;
                  $page_max = $numofpages;
              }
      
              $page_min = ($page_min < 1) ? 1 : $page_min;
      
              //$page_content .= '<p class="menuPage">';
      
              if ( ($page_num > ($range - $range_min)) && ($numofpages > $range) ) {
                  $page_pagination .= '<a title="First" href="'.$self.'&page=1">&lt;</a> ';
              }
      
              if ($page_num != 1) {
                  $page_pagination .= '<a href="'.$self.'&page='.($page_num-1). '">Previous</a> ';
              }
      
              for ($i = $page_min;$i <= $page_max;$i++) {
                  if ($i == $page_num)
                  $page_pagination .= '<strong>' . $i . '</strong> ';
                  else
                  $page_pagination.= '<a href="'.$self.'&page='.$i. '">'.$i.'</a> ';
              }
      
              if ($page_num < $numofpages) {
                  $page_pagination.= ' <a href="'.$self.'&page='.($page_num + 1) . '">Next</a>';
              }
      
      
              if (($page_num< ($numofpages - $range_max)) && ($numofpages > $range)) {
                  $page_pagination .= ' <a title="Last" href="'.$selft.'&page='.$numofpages. '">&gt;</a> ';
              }
              $page['PAGINATION'] ='<p id="pagination">'.$page_pagination.'</p>';
          }//end if more than 1 page
      echo $page_pagination;
      // and close the database connection
      mysql_close($con);
      

        Just a tip, don't mix 0 and "0", one is a string and the other is a number

          you can drop this line as your not using it
          $page['PAGINATION'] ='<p id="pagination">'.$page_pagination.'</p>';

            echo $page_pagination; is fine, in my case i was just reasigning it to the array element

              3 months later

              Hey ya'll I'm a long time lurker and first time poster, but I just wanted to give you a big thanks for the code Dagon. I'm still pretty much a newbie to PHP and was working on my own pagination system, but saw this thread and played with your code. Had to make some modifications here and there but now it works perfectly on my site, so thank you very much for the help!

                10 days later

                Dagon: thanks for your sliding pagination bar code. I took it, applied my standard axxx-retentive coding conventions, and added a table version. Works great!

                Note: if you enable (un-comment) the instrumentation code, you can watch it work.

                <?php
                
                // Script name: pageBar.php
                //	generates sliding pagination bar
                //	derived from very nice PHP script posted by Dagon 080418 (thanks!)
                	// @var int _GET["s"] => requested page number
                	// @var int _GET["c"] => # of line item (i.e., row) at top of requested pager
                
                //	This script is, I believe, strict PHP[4-5] code compliant (a highly desireable characteristic):
                //		1.  execution of this script will generate NO PHP warnings (which distract the amazing Zend engine); and
                //		2.  the HTML generated by this script will generate NO errors when checked with BBEdit (simply the BEST).
                
                //	This script may appear to some as overkill, but I have been programming since 1963 and learned early
                //		the value of taking the time to make your code as regular and readable as you possibly can:
                //		-- CONSTANTS are always full upper case
                //		-- caMel variable names rather than under_scored to distinguish from PHP constructs, e.g., ini_set
                //		-- the first letter of most variable names will indicate the "normal" type: i => int; a => array; s => string
                //		-- variables are explicitly initialized to avoid PHP warnings
                //		-- whenever a calculation may deliver a float to a non-float variable, explicitly type the delivered result, e.g., (int)
                //		-- GET (and POST) variable retrieval is always conditional to avoid PHP warnings
                //		-- conditional {braces} are ALWAYS on separate lines AND lined up vertically to make balancing visually easy
                //		-- for clarity, all operators have leading and trailing spaces,
                //				EXCEPT.concatenate.because ". =" doesn't work (so, for consistency, NEVER use spaces for the.operator)
                //		-- C++ style comments, with in-line preferred whenever possible
                //		-- leading tabs rather than spaces (marginally faster to parse) -- this one is controversial
                //		-- maintain separate and distinct tabbing sequences for PHP and HTML code snippets, and, except for embedded snippets,
                //				left align language shift constructs to make them easily identifiable (contrast, e.g., lines 1 and 142, and line 167)
                //		-- all HTML tags are balanced and full lower case per the W3C standard
                //		-- all HTML generated by this script has been "prettified" to make it easier to read/debug
                
                //	My coding conventions will not appeal to all, but opinions are rather like, uh, noses ... (almost) everyone has one.
                //  However, I have built, and daily maintain, 7 APACHE+PHP+MySQL websites, comprising tens of thousands of lines of
                //  PHP+MySQL+HTML code using these conventions.  If anything, my standards are higher today than ever before,
                //	especially when it relates to site security: all of my site pages are generated dynamically, and, more importantly,
                //	visitor/guest/user access is controlled at both application AND page levels.  My goal is not glitz but fast-as-possible
                //	download/rendering, which is just fine for my clients since my sites are working sites not consumer-oriented marketing hoses.
                //
                //	icehose 080802
                
                //	OK, enough soap box, here's the beef ...
                
                // here's a simple error logging function to facilitate debugging (aka, "instrumentation")
                	// @var string $sMessage => string to be written to error log
                function logExc($sMessage)
                {
                	$_sMsg = (string) date("j F Y, g:i a: ");
                	$_sMsg .= (string) $sMessage;
                	$_sMsg .= (string) "\n";
                	error_log($_sMsg, 3, "errors.log"); // change to direct output to your preferred log file location
                } // end logExc
                
                //---- start optional
                	// set php configuration variables to illustrate strict compliance
                	//		strongly advisable during code development and debugging!
                	ini_set("track_errors", "1"); // error tracking
                	error_reporting(E_ALL); // enable error notices
                //---- end optional
                
                // script constants (could/should be in .cfg file)
                $ROWCOUNT = 25; // # rows per page (set by you)
                $RANGE = 10; // number of page numbers in pageBar (set by you)
                
                // calculate local control constants (could/should be precalculated and stored as CONSTANTS in .cfg file)
                //$iRangeMin = (int) ($RANGE % 2 == 0) ? ($RANGE / 2) - 1 : ($RANGE - 1) / 2; // Dagon's elegant original
                //$iRangeMax = (int) ($RANGE % 2 == 0) ? $iRangeMin + 1 : $iRangeMin; // Dagon's elegant original
                if ($RANGE % 2 == 0) // calculate modulo only once for both constants
                {
                	$iRangeMin = (int) ($RANGE / 2) - 1;
                	$iRangeMax = $iRangeMin + 1;
                }
                else
                {
                	$iRangeMin = (int) ($RANGE - 1) / 2;
                	$iRangeMax = $iRangeMin;
                }
                
                // GET working variables
                $iPageNum = 1; // set default page number
                if (!empty($_GET["s"])) // page number passed via GET
                {
                	$iPageNum = $_GET["s"]; // get actual page number
                }
                $iCursor = 0; // set default page cursor
                if (!empty($_GET["cursor"])) // cursor passed via GET
                {
                	$iCursor = $_GET["cursor"]; // get actual cursor value
                }
                
                // Remember that databases, e.g., MySQL, have no concept of "page", so passing both page # AND cursor
                //	via your URL guarantees that you immediately have the page # info you need to generate the next pagination bar
                //	AND the LIMIT info you need to launch your next query (I prefer this to generating one from the other)
                
                // set initial value(s)
                //		Note: here is where you set the actual size of the data set using, e.g., a MySQL query
                //		Change this value manually to see the effects this number has on the pagination bar
                $iRows = 515; // total # of rows in data set
                
                // calculate local control variables
                $iPages = (int) ceil($iRows / $ROWCOUNT);
                $iPageMin = $iPageNum - $iRangeMin;
                $iPageMax = $iPageNum + $iRangeMax;
                $iPageMin = ($iPageMin < 1) ? 1 : $iPageMin;
                $iPageMax = ($iPageMax < ($iPageMin + $RANGE - 1)) ? $iPageMin + $RANGE - 1 : $iPageMax;
                
                // create two different versions of pagination bar: <div>...</div> and <table>...</table>
                $sPageButtons = ""; // set default (for strict correctness)
                if ($iPages > 1 ) // we need to generate a pagination bar
                {
                	if ($iPageMax > $iPages)
                	{
                		$iPageMin = ($iPageMin > 1) ? $iPages - $RANGE + 1 : 1;
                		$iPageMax = $iPages;
                	}
                	$iPageMin = ($iPageMin < 1) ? 1 : $iPageMin;
                	$s = 0; // initialize
                	$c = 0; // initialize
                	$p = 0; // initialize
                	if (($iPageNum > ($RANGE - $iRangeMin)) && ($iPages > $RANGE)) // generate left arrow button
                	{
                		$s = 1; // pro forma
                //		logExc("<: s = ".$s."; c = ".$c); // debugging instrumentation
                		$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=1&cursor=0\">&lt;</a></td>\r";
                		$sPageButtons .= "\t\t<a href=\"pageBar.php?s=1&cursor=0\">&lt;</a>\r";
                	}
                	if ($iPageNum > ($iRangeMin + 1)) // generate Prev button
                	{
                		$s = $iPageMin - 1;
                		$c = ($s - 1) * $ROWCOUNT;
                //		logExc("Prev: s = ".$s."; c = ".$c); // debugging instrumentation
                		$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Prev</a></td>\r";
                		$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Prev</a>\r";
                	}
                	for ($i = $iPageMin; $i <= $iPageMax; $i++) // generate numbered buttons
                	{
                		if ($i == $iPageNum)
                		{
                			$s = $i;
                			$c = ($s - 1) * $ROWCOUNT;
                //			logExc($s.": s = ".$s."; c = ".$c); // debugging instrumentation
                			$aPageButtons[++$p] = "<td><b>".$i."</b></td>\r";
                			$sPageButtons .= "\t\t<span><b>".$i."</b></span>\r";
                		}
                		else
                		{
                			$s = $i;
                			$c = ($s - 1) * $ROWCOUNT;
                //			logExc($s.": s = ".$s."; c = ".$c); // debugging instrumentation
                			$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">".$i."</a></td>\r";
                			$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">".$i."</a>\r";
                		}
                	}
                	if (($iPageNum < ($iPages - $iRangeMax)) && ($iPages > $RANGE)) // generate Next button
                	{
                		$s = $iPageMax + 1;
                		$c = ($s - 1) * $ROWCOUNT;
                //		logExc("Next: s = ".$s."; c = ".$c); // debugging instrumentation
                		$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Next</a></td>\r";
                		$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Next</a>\r";
                	}
                	if (($iPageNum < ($iPages - $iRangeMax)) && ($iPages > $RANGE) && ($s < $iPages)) // generate right arrow button
                	{
                		$s = $iPages;
                		$c = ($s - 1) * $ROWCOUNT;
                //		logExc(">: s = ".$s."; c = ".$c); // debugging instrumentation
                		$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">&gt;</a></td>\r";
                		$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">&gt;</a>\r";
                	}
                	$aPage["PAGINATION"] = "\t<div align=\"center\">\r".$sPageButtons."\t</div>\r"; // build <div>...</div> form
                } // end generation of pagination bar
                
                // send headers
                HEADER("Expires: Sun, 15 Dec 2008 00:00:00 GMT");
                HEADER("Cache-Control: no-store, no-cache, must-revalidate");
                HEADER("Pragma: no-cache");
                
                // start output to browser
                ?>
                <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xHTML1/DTD/xHTML1-Transitional.dTD">
                <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
                <!--| VERSION 1.0 |-->
                <head>
                	<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
                	<title>Sliding Pagination Bar Demo</title>
                </head>
                <body>
                	<p align="center"><b><u>Sliding Pagination Bar Demo</u></b></p>
                <?php
                echo $aPage["PAGINATION"];  // display <div>...</div> form
                
                // build/display <table>...</table> form
                //		Note: if your page is already in table format, you can delete the <table ...> and </table> lines
                //			  leaving only the <tr> thru </tr> lines ... unless you need the align="center" table attribute
                ?>
                	<table align="center">
                		<tr>
                <?php
                foreach ($aPageButtons as $sPageButton)
                {
                	if (!empty($sPageButton))
                	{
                ?>
                			<?php print $sPageButton ?>
                <?php
                	}
                }
                
                // close output to browser
                ?>
                		</tr>
                	</table>
                </body>
                </html>

                  As happens too often, I woke up this am and realized that, while I slept, my brain had conceived a somewhat more efficient control structure for Dagon's sliding pagination bar. It took only a few minutes to implement and debug. Here's the new, improved sliding pagination bar (with new code annotated):

                  <?php
                  
                  // Script name: pageBar.php
                  //	generates sliding pagination bar
                  //	derived from very nice PHP script posted by Dagon 080418 (thanks!)
                  	// @var int _GET["s"] => requested page number
                  	// @var int _GET["c"] => # of line item (i.e., row) at top of requested pager
                  
                  //  [soap box deleted to comply with PHPBuilder size restrictions - icehose 080803]
                  
                  //	icehose 080802
                  
                  // here's a simple error logging function to facilitate debugging (aka, "instrumentation")
                  	// @var string $sMessage => string to be written to error log
                  function logExc($sMessage)
                  {
                  	$_sMsg = (string) date("j F Y, g:i a: ");
                  	$_sMsg .= (string) $sMessage;
                  	$_sMsg .= (string) "\n";
                  	error_log($_sMsg, 3, "errors.log"); // change to direct output to your preferred log file location
                  } // end logExc
                  
                  //---- start optional
                  	// set php configuration variables to illustrate strict compliance
                  	//		strongly advisable during code development and debugging!
                  	ini_set("track_errors", "1"); // error tracking
                  	error_reporting(E_ALL); // enable error notices
                  //---- end optional
                  
                  // script constants (could/should be in .cfg file)
                  $ROWCOUNT = 25; // # rows per page (set by you)
                  $RANGE = 10; // number of page numbers in pageBar (set by you)
                  
                  // calculate local control constants (could/should be precalculated and stored as CONSTANTS in .cfg file)
                  //$iRangeMin = (int) ($RANGE % 2 == 0) ? ($RANGE / 2) - 1 : ($RANGE - 1) / 2; // Dagon's elegant original
                  //$iRangeMax = (int) ($RANGE % 2 == 0) ? $iRangeMin + 1 : $iRangeMin; // Dagon's elegant original
                  if ($RANGE % 2 == 0) // calculate modulo only once for both constants
                  {
                  	$iRangeMin = (int) ($RANGE / 2) - 1;
                  	$iRangeMax = $iRangeMin + 1;
                  }
                  else
                  {
                  	$iRangeMin = (int) ($RANGE - 1) / 2;
                  	$iRangeMax = $iRangeMin;
                  }
                  
                  // GET working variables
                  $iPageNum = 1; // set default page number
                  if (!empty($_GET["s"])) // page number passed via GET
                  {
                  	$iPageNum = $_GET["s"]; // get actual page number
                  }
                  $iCursor = 0; // set default page cursor
                  if (!empty($_GET["cursor"])) // cursor passed via GET
                  {
                  	$iCursor = $_GET["cursor"]; // get actual cursor value
                  }
                  
                  // Remember that databases, e.g., MySQL, have no concept of "page", so passing both page # AND cursor
                  //	via your URL guarantees that you immediately have the page # info you need to generate the next pagination bar
                  //	AND the LIMIT info you need to launch your next query (I prefer this to generating one from the other)
                  
                  // set initial value(s)
                  //		Note: here is where you set the actual size of the data set using, e.g., a MySQL query
                  //		Change this value manually to see the effects this number has on the pagination bar
                  $iRows = 515; // total # of rows in data set
                  
                  // calculate local control variables
                  $iPages = (int) ceil($iRows / $ROWCOUNT);
                  
                  //---- Start new code
                  // Dagon's original code calculated the following control variables using a round-about technique;
                  //		however, the same variables can be calculated directly from page # and base constants as follows:
                  if ($iPageNum < ($iRangeMax + 1)) // ramp up phase
                  {
                  	$iPageMin = 1;
                  	$iPageMax = $RANGE;
                  }
                  else // stable state, with min function to take care of ramp down phase
                  {
                  	$iPageMin = min(($iPageNum - $iRangeMin), ($iPages - ($RANGE - 1)));
                  	$iPageMax = min(($iPageNum + $iRangeMax), $iPages);
                  }
                  //---- End new code
                  
                  // create two different versions of pagination bar: <div>...</div> and <table>...</table>
                  $sPageButtons = ""; // set default (for strict correctness)
                  if ($iPages > 1 ) // we need to generate a pagination bar
                  {
                  	$s = 0; // initialize
                  	$c = 0; // initialize
                  	$p = 0; // initialize
                  	if ($iPageMin > 1) // generate at least Prev button (New: simplified control structure)
                  	{
                  		if ($iPageMin > 2) // but first generate left arrow button (New: simplified control structure)
                  		{
                  			$s = 1; // pro forma
                  //			logExc("<: s = ".$s."; c = ".$c); // debugging instrumentation
                  			$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=1&cursor=0\">&lt;</a></td>\r";
                  			$sPageButtons .= "\t\t<a href=\"pageBar.php?s=1&cursor=0\">&lt;</a>\r";
                  		}
                  		$s = $iPageMin - 1;
                  		$c = ($s - 1) * $ROWCOUNT;
                  //		logExc("Prev: s = ".$s."; c = ".$c); // debugging instrumentation
                  		$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Prev</a></td>\r";
                  		$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Prev</a>\r";
                  	}
                  	for ($i = $iPageMin; $i <= $iPageMax; $i++) // generate numbered buttons
                  	{
                  		if ($i == $iPageNum)
                  		{
                  			$s = $i;
                  			$c = ($s - 1) * $ROWCOUNT;
                  //			logExc($s.": s = ".$s."; c = ".$c); // debugging instrumentation
                  			$aPageButtons[++$p] = "<td><b>".$i."</b></td>\r";
                  			$sPageButtons .= "\t\t<span><b>".$i."</b></span>\r";
                  		}
                  		else
                  		{
                  			$s = $i;
                  			$c = ($s - 1) * $ROWCOUNT;
                  //			logExc($s.": s = ".$s."; c = ".$c); // debugging instrumentation
                  			$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">".$i."</a></td>\r";
                  			$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">".$i."</a>\r";
                  		}
                  	}
                  	if ($iPageMax < $iPages) // generate Next button (New: simplified control structure)
                  	{
                  		$s = $iPageMax + 1;
                  		$c = ($s - 1) * $ROWCOUNT;
                  //		logExc("Next: s = ".$s."; c = ".$c); // debugging instrumentation
                  		$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Next</a></td>\r";
                  		$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Next</a>\r";
                  		if ($s < $iPages) // also generate right arrow button (New: simplified control structure)
                  		{
                  			$s = $iPages;
                  			$c = ($s - 1) * $ROWCOUNT;
                  //			logExc(">: s = ".$s."; c = ".$c); // debugging instrumentation
                  			$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">&gt;</a></td>\r";
                  			$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">&gt;</a>\r";
                  		}
                  	}
                  	$aPage["PAGINATION"] = "\t<div align=\"center\">\r".$sPageButtons."\t</div>\r"; // build <div>...</div> form
                  } // end generation of pagination bar
                  
                  // send headers
                  HEADER("Expires: Sun, 15 Dec 2008 00:00:00 GMT");
                  HEADER("Cache-Control: no-store, no-cache, must-revalidate");
                  HEADER("Pragma: no-cache");
                  
                  // start output to browser
                  ?>
                  <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xHTML1/DTD/xHTML1-Transitional.dTD">
                  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
                  <!--| VERSION 1.0 |-->
                  <head>
                  	<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
                  	<title>Sliding Pagination Bar Demo</title>
                  </head>
                  <body>
                  	<p align="center"><b><u>Sliding Pagination Bar Demo</u></b></p>
                  <?php
                  echo $aPage["PAGINATION"];  // display <div>...</div> form
                  
                  // build/display <table>...</table> form
                  //		Note: if your page is already in table format, you can delete the <table ...> and </table> lines
                  //			  leaving only the <tr> thru </tr> lines ... unless you need the align="center" table attribute
                  ?>
                  	<table align="center">
                  		<tr>
                  <?php
                  foreach ($aPageButtons as $sPageButton)
                  {
                  	if (!empty($sPageButton))
                  	{
                  ?>
                  			<?php print $sPageButton ?>
                  <?php
                  	}
                  }
                  
                  // close output to browser
                  ?>
                  		</tr>
                  	</table>
                  </body>
                  </html>

                    sorry, guys, but I screwed the pooch. I did my testing assuming big data sets, but then, AFTER my last post, I went to actually install the code in a working page, only to discover that the code broke with small data sets (i.e., requiring less than RANGE buttons)! Here's the (I think) corrected [and annotated] code:

                    <?php
                    
                    // Script name: pageBar.php
                    //	generates sliding pagination bar
                    //	derived from very nice PHP script posted by Dagon 080418 (thanks!)
                    	// @var int _GET["s"] => requested page number
                    	// @var int _GET["c"] => # of line item (i.e., row) at top of requested pager
                    
                    //	[icehose 080803: soap box deleted to comply with PHPBuilder size restrictions]
                    
                    // here's a simple error logging function to facilitate debugging (aka, "instrumentation")
                    	// @var string $sMessage => string to be written to error log
                    function logExc($sMessage)
                    {
                    	$_sMsg = (string) date("j F Y, g:i a: ");
                    	$_sMsg .= (string) $sMessage;
                    	$_sMsg .= (string) "\n";
                    	error_log($_sMsg, 3, "errors.log"); // change to direct output to your preferred log file location
                    } // end logExc
                    
                    //---- start optional
                    	// set php configuration variables to illustrate strict compliance
                    	//		strongly advisable during code development and debugging!
                    	ini_set("track_errors", "1"); // error tracking
                    	error_reporting(E_ALL); // enable error notices
                    //---- end optional
                    
                    // script constants (could/should be in .cfg file) [icehose 08083: converted to defines]
                    define("ROWCOUNT", 25); // # rows per page (set by you)
                    define("RANGE", 10); // number of page numbers in pageBar (set by you)
                    
                    // GET working variables
                    $iPageNum = 1; // set default page number
                    if (!empty($_GET["s"])) // page number passed via GET
                    {
                    	$iPageNum = $_GET["s"]; // get actual page number
                    }
                    $iCursor = 0; // set default page cursor
                    if (!empty($_GET["cursor"])) // cursor passed via GET
                    {
                    	$iCursor = $_GET["cursor"]; // get actual cursor value
                    }
                    
                    // Remember that databases, e.g., MySQL, have no concept of "page", so passing both page # AND cursor
                    //	via your URL guarantees that you immediately have the page # info you need to generate the next pagination bar
                    //	AND the LIMIT info you need to launch your next query (I prefer this to generating one from the other)
                    
                    // set initial value(s)
                    //		Note: here is where you set the actual size of the data set using, e.g., a MySQL query
                    //		Change this value manually to see the effects this number has on the pagination bar
                    $iRows = 115; // total # of rows in data set
                    
                    //---- [icehose 080803a: start corrected code]
                    // calculate local control variables
                    $iPages = (int) ceil($iRows / ROWCOUNT);
                    $iRange = min($iPages, RANGE); // compensates for small data sets
                    if ($iRange % 2 == 0) // calculate modulo only once for both constants
                    {
                    	$iRangeMin = (int) ($iRange / 2) - 1;
                    	$iRangeMax = $iRangeMin + 1;
                    }
                    else
                    {
                    	$iRangeMin = (int) ($iRange - 1) / 2;
                    	$iRangeMax = $iRangeMin;
                    }
                    //---- [icehose 080803a: end corrected code]
                    
                    //---- Start new code
                    // Dagon's original code calculated the following control variables using a round-about technique;
                    //		however, the same variables can be calculated directly from page # and base constants as follows:
                    if ($iPageNum < ($iRangeMax + 1)) // ramp up phase
                    {
                    	$iPageMin = 1;
                    	$iPageMax = $iRange;
                    }
                    else // stable state, with min function to take care of ramp down phase
                    {
                    	$iPageMin = min(($iPageNum - $iRangeMin), ($iPages - ($iRange - 1)));
                    	$iPageMax = min(($iPageNum + $iRangeMax), $iPages);
                    }
                    //---- End new code
                    
                    // create two different versions of pagination bar: <div>...</div> and <table>...</table>
                    $sPageButtons = ""; // set default (for strict correctness)
                    if ($iPages > 1 ) // we need to generate a pagination bar
                    {
                    	$s = 0; // initialize
                    	$c = 0; // initialize
                    	$p = 0; // initialize
                    	if ($iPageMin > 1) // generate at least Prev button (New: simplified control structure)
                    	{
                    		if ($iPageMin > 2) // but first generate left arrow button (New: simplified control structure)
                    		{
                    			$s = 1; // pro forma
                    //			logExc("<: s = ".$s."; c = ".$c); // debugging instrumentation
                    			$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=1&cursor=0\">&lt;</a></td>\r";
                    			$sPageButtons .= "\t\t<a href=\"pageBar.php?s=1&cursor=0\">&lt;</a>\r";
                    		}
                    		$s = $iPageMin - 1;
                    		$c = ($s - 1) * ROWCOUNT;
                    //		logExc("Prev: s = ".$s."; c = ".$c); // debugging instrumentation
                    		$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Prev</a></td>\r";
                    		$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Prev</a>\r";
                    	}
                    	for ($i = $iPageMin; $i <= $iPageMax; $i++) // generate numbered buttons
                    	{
                    		if ($i == $iPageNum)
                    		{
                    			$s = $i;
                    			$c = ($s - 1) * ROWCOUNT;
                    //			logExc($s.": s = ".$s."; c = ".$c); // debugging instrumentation
                    			$aPageButtons[++$p] = "<td><b>".$i."</b></td>\r";
                    			$sPageButtons .= "\t\t<span><b>".$i."</b></span>\r";
                    		}
                    		else
                    		{
                    			$s = $i;
                    			$c = ($s - 1) * ROWCOUNT;
                    //			logExc($s.": s = ".$s."; c = ".$c); // debugging instrumentation
                    			$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">".$i."</a></td>\r";
                    			$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">".$i."</a>\r";
                    		}
                    	}
                    	if ($iPageMax < $iPages) // generate Next button (New: simplified control structure)
                    	{
                    		$s = $iPageMax + 1;
                    		$c = ($s - 1) * ROWCOUNT;
                    //		logExc("Next: s = ".$s."; c = ".$c); // debugging instrumentation
                    		$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Next</a></td>\r";
                    		$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">Next</a>\r";
                    		if ($s < $iPages) // also generate right arrow button (New: simplified control structure)
                    		{
                    			$s = $iPages;
                    			$c = ($s - 1) * ROWCOUNT;
                    //			logExc(">: s = ".$s."; c = ".$c); // debugging instrumentation
                    			$aPageButtons[++$p] = "<td><a href=\"pageBar.php?s=".$s."&cursor=".$c."\">&gt;</a></td>\r";
                    			$sPageButtons .= "\t\t<a href=\"pageBar.php?s=".$s."&cursor=".$c."\">&gt;</a>\r";
                    		}
                    	}
                    	$aPage["PAGINATION"] = "\t<div align=\"center\">\r".$sPageButtons."\t</div>\r"; // build <div>...</div> form
                    } // end generation of pagination bar
                    
                    // send headers
                    HEADER("Expires: Sun, 15 Dec 2008 00:00:00 GMT");
                    HEADER("Cache-Control: no-store, no-cache, must-revalidate");
                    HEADER("Pragma: no-cache");
                    
                    // start output to browser
                    ?>
                    <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xHTML1/DTD/xHTML1-Transitional.dTD">
                    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
                    <!--| VERSION 1.0 |-->
                    <head>
                    	<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
                    	<title>Sliding Pagination Bar Demo</title>
                    </head>
                    <body>
                    	<p align="center"><b><u>Sliding Pagination Bar Demo</u></b></p>
                    <?php
                    echo $aPage["PAGINATION"];  // display <div>...</div> form
                    
                    // build/display <table>...</table> form
                    //		Note: if your page is already in table format, you can delete the <table ...> and </table> lines
                    //			  leaving only the <tr> thru </tr> lines ... unless you need the align="center" table attribute
                    ?>
                    	<table align="center">
                    		<tr>
                    <?php
                    foreach ($aPageButtons as $sPageButton)
                    {
                    	if (!empty($sPageButton))
                    	{
                    ?>
                    			<?php print $sPageButton ?>
                    <?php
                    	}
                    }
                    
                    // close output to browser
                    ?>
                    		</tr>
                    	</table>
                    </body>
                    </html>
                      5 years later
                      require 'connect.inc.php'; //require database connection file
                      
                      $per_page = 5;
                      $pages_query = *mysql_query("SELECT COUNT('id') FROM mytable");
                      $num_of_pages = ceil(mysql_result($pages_query, 0)/$per_page);
                      
                      
                      
                      
                      $curr_page = (isset($_GET['page']))? (int)$_GET['page'] : 1;
                      $start = ($curr_page - 1) * $per_page;
                      
                      
                      
                      
                      $query = "SELECT id, name FROM mytable LIMIT $start, $per_page";
                      $query_run = mysql_query($query) or die($error.mysql_error());
                      while($row = mysql_fetch_assoc($query_run)){
                      	$id = $row['id'];
                      	$name = $row['name'];
                      	echo "<p>".$id.". ".$name."</p>";//you can display whatever you want here from your table
                      
                      }
                      echo "<hr>";
                      if(($curr_page-2)==0){
                      	$range_min = $curr_page-1;
                      	$range_max = $curr_page+3;
                      	}
                      	else if(($curr_page-1)==0){
                      		$range_min = $curr_page;
                      		$range_max = $curr_page+4;
                      		}
                      			else if(($curr_page+1)==$num_of_pages){
                      			$range_min = $curr_page-3;
                      			$range_max = $curr_page+1;
                      			}
                      				else if($curr_page==$num_of_pages){
                      				$range_min = $curr_page-4;
                      				$range_max = $curr_page;
                      				}
                      				else{
                      					$range_min = $curr_page-2;
                      					$range_max = $curr_page+2;
                      					}
                      if($num_of_pages>1 && $curr_page<=$num_of_pages){
                      echo "<a href=\"?page=1\">First</a>... ";	
                      
                      
                      
                      
                      if($curr_page>1&&$curr_page<$num_of_pages){	
                      echo "<a href=\"?page=".($curr_page-1)."\">Prev</a> ";
                      for($x=$range_min;$x<=$range_max;$x++){
                      
                      
                      
                      
                      //to make the current page link bold
                      echo ($x==$curr_page)?"<b><a href=\"?page=".$x."\">".$x."</a></b> " : "<a href=\"?page=".$x."\">".$x."</a> " ;
                      }
                      echo "<a href=\"?page=".($curr_page+1)."\">Next</a> ";
                      }
                      
                      
                      
                      
                      else if($curr_page==1){
                      for($x=$range_min;$x<=$range_max;$x++){
                      
                      
                      
                      
                      //to make the current page link bold
                      echo ($x==$curr_page)?"<b><a href=\"?page=".$x."\">".$x."</a></b> " : "<a href=\"?page=".$x."\">".$x."</a> " ;
                      }
                      echo "<a href=\"?page=".($curr_page+1)."\">Next</a> ";	
                      }
                      else if($curr_page==$num_of_pages){
                      echo "<a href=\"?page=".($curr_page-1)."\">Prev</a> ";
                      for($x=$range_min;$x<=$range_max;$x++){
                      
                      
                      
                      
                      //to make the current page link bold
                      echo ($x==$curr_page)?"<b><a href=\"?page=".$x."\">".$x."</a></b> " : "<a href=\"?page=".$x."\">".$x."</a> " ;
                      }*
                      }
                      echo "...<a href=\"?page=".$num_of_pages."\">Last</a>";
                      *}
                      ?>
                      ScoobyDooobyD00;10863166 wrote:

                      I've spent a couple of hours trying to figure this out.

                      I found a tutorial http://www.php-mysql-tutorial.com/php-mysql-paging.php that is really close to what I want except it doesn't stop creating numbers. For instance if I have 300 pages then it would do this.

                      1 2 3 4 5 6 7 ... 300

                      I want to have it so if the user is on the first page then it will echo out the next 9 numbers.
                      Example:

                      1 2 3 4 5 6 7 8 9 10 Next

                      Or if they're on page 15 it will echo out the previous 5 numbers and the next 5 numbers.
                      Example:
                      Prev 10 11 12 13 14 15 16 17 18 19 20 Next

                      and last if they're on the last page it would look like this

                      Prev 290 291 292 293 294 295 296 297 298 299 300

                      Please don't send me to google. I've googled "php paging like google" "pagination like google with php" and every other way I can think of.

                      Thanks in advance!

                        Write a Reply...