Code for Paging like Page 1 of 5

I need help in coding for the First, Previous, Paging, Next, Last. Theirs somebody has an idea on that?

Any help is highly appreciated…

Thank you

This is called Pagination and it all depends on where you are getting your data from.
If you are using MySQL you should look at LIMIT.
e.g. SELECT * FROM table LIMIT 10,20

Read this Perfect PHP Pagination Article » SitePoint

Yes, the data is from the database…my boss want is I have a hyperlink First Previous Page 1 of 5 Next Last. and I really font know how can I do that.

Here is my code:


<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Machine 1 Problem</title>
<script type="text/JavaScript">
 
FUNCTION confirmDelete(){
VAR agree=CONFIRM("Are you sure you want to delete this file?");
IF (agree)
     RETURN TRUE ;
ELSE
     RETURN FALSE ;
}
</script>
</head>

<body>
<form method="post" action="test1.php" name="machine1">
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_name = 'db_machine1';

$query = mysql_connect("$db_host", "$db_user")or die (mysql_error());
$db = mysql_select_db("$db_name")or die (mysql_error());

$query = "SELECT * FROM tbl_machine1 ORDER BY Emp_ID ASC";
$result = mysql_query($query) or die(mysql_error());

echo "<table border='1'><tr>";
for($i = 0; $i < mysql_num_fields($result); $i++){
	echo "<th>".mysql_field_name($result, $i)."</th>";
	//echo "<th><a>.mysql_field_name($result, $i).""</a></th>";
}
echo "<th>Options</th>";
echo "</tr>";
while($row = mysql_fetch_array($result)){
	echo "<tr>";
	for($i = 0; $i < mysql_num_fields($result); $i++){
		echo "<td>". $row[$i] ."</td>";
	}
	echo "<td><a href = 'edit.php'>Edit</a> <a href = 'delete.php' onClick='confirmDelete()';>Delete</a></td>";
	echo "</tr>";
}

echo "</table>";
echo "<input type = 'button' name= 'add' value='ADD'>";

?>
</form>
</body>
</html>

I got this code from other forum


<?php
session_start();
//----------------------------------------------------------------------------------------------------------------------
//connect to the database
$DBUserName = "root";     //database user account name
$DBPassword = "";     //database user account password
$DBName = "test";   //name of database

@$conn = mysql_connect("localhost", $DBUserName, $DBPassword) or die('<br />1-Cannot connect to the database at the moment.<br /><br />Please try again later.<br />');  //connect to mysql
@$isDbSelected = mysql_select_db($DBName, $conn) or die('<br />1-Cannot connect to the database at the moment.<br /><br />Please try again later.<br />');        //connect to the db
//----------------------------------------------------------------------------------------------------------------------

include('Paginator.php');

if (!isset($_SESSION['pageMaker'])) {
    $linesPerPage = 5;   //number of lines to print per page
    $numLinksDisplay = 5;    //number of page links to display at a time
    $query = 'select * from tblperson';
    $pageMaker = new Paginator($linesPerPage, $numLinksDisplay, $query, $conn);
} else {
    $pageMaker = unserialize($_SESSION['pageMaker']);
}

//set current page
if (isset($_GET['type']))
    $pageMaker->setCurrPage($_GET['type'], $_GET['txtPgNum']);

//------------------------------------------------------------
//Code to retrieve the rows to display on the current page
//------------------------------------------------------------
if (!$rs = $pageMaker->getPageRecords($conn))
    die('<p>**ERROR - cannot get records for the page at the moment.</p>');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>Pagination</title>
        <!-- add the stylesheet for the page links -->
        <?php echo $pageMaker->getLinkStyles(); ?>
    </head>
    <body>
        <!-- Display the page links -->
        <div id="page_links_wrapper">
            <?php echo $pageMaker->showLinks(); ?>
        </div>
        <!-- Code block to display the DB records for this page-->
        <table>
            <?php
            while ($row = mysql_fetch_assoc($rs)) {
                echo '<tr><td>' . $row['fldPersonID'] . '</td><td>' . $row['fldGivenName'] . '</td><td>' . $row['fldFamilyName'] . '</td></tr>';
            }
            mysql_free_result($rs);
            mysql_close($conn);
            ?>
        </table>
        <!-- End of code block to display the DB records for this page-->
        <?php
//hide or display the 'previous' and 'next' buttons as required
            $pageMaker->applyLinkStyles();
//serialise the session's pageMaker object for the next call to this page
            $_SESSION['pageMaker'] = serialize($pageMaker);
        ?>
    </body>
</html>

Paginator.php


ve <?php

class Paginator {

   // Properties
    protected $linesPerPage;    //number of lines to print per page
    protected $numLinksDisplay;    //number of page links to display at a time
    protected $query;
    protected $currPage;
    protected $totRows;
    protected $totPages;
    protected $offset;
    /*     * *********************************************************************
      Class Constructor
     * ********************************************************************* */
    public function __construct($numLines, $numLinks, $query, $conn) {
        $this->linesPerPage = ceil($numLines);
        $this->numLinksDisplay = ceil($numLinks);
        $this->query = $query;
        $this->currPage = 1;
        $this->offset = 0;

        $this->initialise($conn);
    }
    /*     * *********************************************************************
      Class Accessor Methods
     * ********************************************************************* */
    public function setQuery($query, $conn) {
        $this->query = $query;
        $this->initialise($conn);
    }
    //-------------------------------------------------------------------------
    public function setCurrPage($type, $pageNum) {
        $pageNum = ceil($pageNum);
        //check which link was clicked
        switch ($type) {
            case 'pageLink':
                $this->currPage = $pageNum;
                break;
            case 'prevNext':
                $this->currPage = $this->currPage + $pageNum;
                if ($this->currPage < 1) {
                    $this->currPage = 1;
                }
                if ($this->currPage > $this->totPages) {
                    $this->currPage = $this->totPages;
                }
                break;
            case 'firstPg':
                $this->currPage = 1;
                break;
            case 'lastPg':
                $this->currPage = $this->totPages;
                break;
        }
        //calculate the offset of the first record number to retrieve from the DB for this page
        $this->offset = ($this->currPage * $this->linesPerPage) - $this->linesPerPage;
        if ($this->offset < 0) {
            $this->offset = 0;
        }
        if ($this->offset > $this->totRows) {
            $this->offset = $this->totRows;
        }
    }
    //-----------------------------------------------
    public function getCurrPage() {
        return $this->currPage;
    }

    /*     * *********************************************************************
      Class Methods
     * ********************************************************************* */
    private function initialise($conn) {
        //count all the records to work out max number of rows and number of pages needed
        $rs = @mysql_query($this->query, $conn) or die("<p>3-Server is busy.<br />Please try again later.</p>");
        $this->totRows = mysql_num_rows($rs); //total number of rows to display
        @mysql_free_result($rs);
        if ($this->totRows % $this->linesPerPage == 0) {
            $this->totPages = $this->totRows / $this->linesPerPage;
        } else {
            $this->totPages = round(($this->totRows / $this->linesPerPage) + 0.5);  //total number of pages required
        }
        $this->numLinksDisplay = ($this->numLinksDisplay > $this->totPages) ? $this->totPages : $this->numLinksDisplay;
        //echo $this->totRows.'<br />'.$this->totPages.'<br />'.$this->numLinksDisplay;  die();
    }
    //-------------------------------------------------------------------------------------
    public function getPageRecords($conn) {
        $query = $this->query . ' limit ' . $this->offset . ',' . $this->linesPerPage;
        $rs = @mysql_query($query, $conn);
        if (!$rs) {
            return false;
        } else {
            return $rs;
        }
    }
    //-------------------------------------------------------------------------------------
    public function showLinks() {
        if ($this->totPages <= 1)
            return;  //no need to display any links
 $str = '<div id="page_links_wrap">' .
                '<div id="page_links_summ">' .
                '<p id="totPages">Total pages: ' . $this->totPages . '</p>' .
                '<p id="totRows">Total records: ' . $this->totRows . '</p>' .
                '</div>' .
                '<div id="page-links-container">' .
                '<ul id="page-links">' .
                '<li id="liFirstPage"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=-1&amp;type=firstPg" title="Click to view first page">First</a></li>' .
                '<li id="liPrevPage"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=-1&amp;type=prevNext" title="Click to view previous page">Previous</a></li>';
        //calculate the min and max link numbers to display for this page
        if ($this->numLinksDisplay % 2 == 0) { //even number of links to display
            $limit1 = $this->currPage - $this->numLinksDisplay / 2;
            $limit2 = $this->currPage + ($this->numLinksDisplay / 2) - 1;
        } else { //odd number of links to display
            $limit1 = $this->currPage - ($this->numLinksDisplay - 1) / 2;
            $limit2 = $this->currPage + ($this->numLinksDisplay - 1) / 2;
        }
        if ($limit1 < 1 && $this->currPage < $this->numLinksDisplay)
            $limit1 = 1;
        if ($limit2 > $this->totPages)
            $limit2 = $this->totPages;
        //adjust the link numbers for when we are within $_SESSION['numLinksDisplay']/2 of either end
        if ($this->currPage <= $this->numLinksDisplay / 2)
            $limit2 = $this->numLinksDisplay;
        if ($this->currPage > $this->totPages - $this->numLinksDisplay / 2)
            $limit1 = $this->totPages - $this->numLinksDisplay + 1;
        //echo '<br />'.$_SESSION['currPage'].'<br />'.$limit1.'<br />'.$limit2.'<br /><br />';
        //display the page links
        for ($i = $limit1; $i <= $limit2; $i = $i + 1) {
            $str = $str . '<li id="liPg' . $i . '"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=' . $i . '&amp;type=pageLink" title="Go to page ' . $i . '">' . $i . '</a></li>';
        }

        $str = $str . '<li id="liNextPage"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=1&amp;type=prevNext" title="Click to view next page">Next</a></li>' .
                '<li id="liLastPage"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=-1&amp;type=lastPg" title="Click to view last page">Last</a></li>' .
                '</ul>' .
                '</div>' .
                '</div>';

        return $str;
    }
    //-------------------------------------------------------------------------------------
    public function getLinkStyles() {
        if ($this->totPages <= 1) {
            return;  //no need to display any links
        }
        $str = '<style type="text/css"> ' .
                '#page_links_wrap {' .
                //'border: 1px solid green; ' .
                'margin: 5px 0px 0px 0px; ' .
                'padding: 0px 0px 0px 0px; ' .
                'width: 270px}' .
                '#page-links-container { ' .
                'font-size: 8pt; ' .
                'font-family: tahoma, arial, sans serif; ' .
                'margin: 0px 0px 0px 0px; ' .
                'padding: 0px 0px 0px 0px} ' .
                '#page-links-container ul { ' .
                'clear: both; ' .
                'padding: 0px 0px 0px 0px; ' .
                'margin: 0px 0px 10px 0px;' .
                'list-style-type: none} ' .
                '#page-links-container ul li { ' .
                'display: inline; ' .
                'color: rgb(0,0,205); ' .
                'padding: 3px 4px 3px 4px; ' .
                'margin: 0px 0px 0px 6px} ' .
                '#page-links-container ul li a { ' .
                'text-decoration: none; ' .
                'font-size: 8pt} ' .
                '#page-links-container ul li a:hover { ' .
                'text-decoration: underline} ' .
                '#page-links-container ul li a:visited { ' .
                'color: rgb(0,0,205);} ' .
                '#page_links_summ { ' .
                'font-size: 8pt; ' .
                'font-family: tahoma, arial, sans serif; ' .
                'overflow: hidden} ' .
                '#totPages { ' .
                //'border: 1px solid blue; ' .
                'margin: 5px 0px 5px 10px; padding: 0px 0px 0px 0px;' .
                'float: left} ' .
                '#totRows { ' .
                //'border: 1px solid red; ' .
                'margin: 5px 10px 5px 0px; padding: 0px 0px 0px 0px;' .
                'float: right} ' .
                '</style> ';
        return $str;
    }
    //--------------------------------------------------------------------------------------
    public function applyLinkStyles() {
        if ($this->totPages <= 1)
            return;  //no need to display any links
            //hide or display the 'previous' and 'next' buttons as required
 if ($this->totPages == 1)
            echo '<script type="text/javascript">document.getElementById("page-links-container").style.display="none";</script>';
        if ($this->currPage == 1) {
            echo '<script type="text/javascript">document.getElementById("liPrevPage").disabled = true;</script>';
        } else {
            echo '<script type="text/javascript">document.getElementById("liPrevPage").disabled = false;</script>';
        }
        if ($this->currPage == $this->totPages) {
            echo '<script type="text/javascript">document.getElementById("liNextPage").disabled = true;</script>';
        } else {
            echo '<script type="text/javascript">document.getElementById("liNextPage").disabled = false;</script>';
        }
        //highlight the current page's page link
        echo '<script type="text/javascript">document.getElementById("liPg' . $this->currPage . '").style.backgroundColor="rgb(200,200,200)";</script>';
        echo '<script type="text/javascript">document.getElementById("liPg' . $this->currPage . '").style.border="1px solid rgb(0,0,0)";</script>';
    }
    //--------------------------------------------------------------------------------------
}
//end of class
?>
Kindly help me how can used this in my codes or how can I add this code on my codes...:(

THank you so much

Why don’t you write your own paging system. I think I’ve posted the code for creating the pager few days ago on this forum. I’ll see if I can find it.

This is my new code with pagination:


 <?php 

 // Connects to your Database 

 mysql_connect("localhost", "root", "") or die(mysql_error()); 

 mysql_select_db("db_machine1") or die(mysql_error()); 

 
 //This checks to see if there is a page number. If not, it will set it to page 1 

 if (!(isset($pagenum))) 

 { 

 $pagenum = 1; 

 } 

 

 //Here we count the number of results 

 //Edit $data to be your query 

 $data = mysql_query("SELECT * FROM tbl_machine1") or die(mysql_error()); 

 $rows = mysql_num_rows($data); 

 

 //This is the number of results displayed per page 

 $page_rows = 4; 

 //$page_rows = 2; 

 //This tells us the page number of our last page 

 $last = ceil($rows/$page_rows); 

 

 //this makes sure the page number isn't below one, or more than our maximum pages 

 if ($pagenum < 1) 

 { 

 $pagenum = 1; 

 } 

 elseif ($pagenum > $last) 

 { 

 $pagenum = $last; 

 } 

 

 //This sets the range to display in our query 

 $max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows; 
 
  //This is your query again, the same one... the only difference is we add $max into it

 $data_p = mysql_query("SELECT * FROM tbl_machine1 $max") or die(mysql_error()); 


 //This is where you display your query results
echo "<table border='1'><tr>";
for($i = 0; $i < mysql_num_fields($data_p); $i++){
	echo "<th>".mysql_field_name($data_p, $i)."</th>";
	//echo "<th><a>.mysql_field_name($result, $i).""</a></th>";
}
echo "<th>Options</th>";
echo "</tr>";
//while($row = mysql_fetch_array($result))
while($info = mysql_fetch_array( $data_p ))
{
	echo "<tr>";
	for($i = 0; $i < mysql_num_fields($data_p); $i++){
		echo "<td>". $info[$i] ."</td>";
		
	}
	echo "<td><a href = 'edit.php'>Edit</a> <a href = 'delete.php' onClick='return confirmDelete();'>Delete</a></td>";
	//echo "<td><a href = 'edit.php'>Edit</a> <a href='delete.php' onclick='return confirm('Are you sure you want to delete?')'>Delete</a</td>";
	echo "</tr>";
}

echo "</table>";
echo "<input type = 'button' name= 'add' value='ADD'>";
// while($info = mysql_fetch_array( $data_p )) 

// { 

// Print $info['Last_Name']; 
// Print $info['First_Name'];
//Print $info['Birthday']; 

// echo "<br>";

 //} 

 echo "<p>";

 
 // This shows the user what page they are on, and the total number of pages

 echo " --Page $pagenum of $last-- <p>";

 
 // First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.

 if ($pagenum == 1) 

 {

 } 

 else 

 {

 echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";

 echo " ";

 $previous = $pagenum-1;

 echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";

 } 


 //just a spacer

 echo " ---- ";


 //This does the same as above, only checking if we are on the last page, and then generating the Next and Last links

 if ($pagenum == $last) 

 {

 } 

 else {

 $next = $pagenum+1;

 echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";

 echo " ";

 echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";

 } 

 ?> 

But the Next and Last hyperlink did not work.

Thank you

Here’s my tiny pagination function, maybe it can be useful …
It shows something like


Back << ..11 12 13 14.. >> Next


function paginate( $d=array(), $a='left' ) 
{
	$out   = ''; 
	$nav   = array( 'first'=>'<<', 'back'=>'Back', 'next'=>'Next', 'last'=>'>>' ); 
	$max   = 8; 
	$page  = ( !empty( $d['page'] ) )  ? $d['page']  : 1; 
	$total = ( !empty( $d['total'] ) ) ? $d['total'] : 0; 
	$limit = ( !empty( $d['limit'] ) ) ? $d['limit'] : 20; 
	$link  = ( !empty( $d['link'] ) )  ? $d['link']  : trim( $_SERVER['PHP_SELF'] ).'?page='; 
	$pages = ( $total > $limit ) ? ceil( $total / $limit ) : 1; 
	$lim   = ( $total < $limit ) ? $total : $limit; 
	$start = ( $page > $max ) ? ( $page - ( $max / 2 ) ) : 1; 
	$end   = ( $start > 1 ) ? ( $start + $max  ) : ( $max + 2 ); 
	//
	if( $pages < 2 || empty( $total ) ){ return; } 
	if( $page > 1 ){ $out .= '<a href="'.$link.( $page - 1 ).'">'.$nav['back'].'</a>'; } 
	if( $page > $max ){ $out .= '<a href="'.$link.'1">'.$nav['first'].'</a>'; } 
	for( $i = 1; $i <= $pages; $i++ ) 
	{
		if( $i >= $start && $i <= $end ){ $out .= ( $i == $page ) ? '<b>'.$i.'</b>' : '<a href="'.$link.$i.'">'.$i.'</a>'; } 
	}
	if( $end < $pages ){ $out .= '<a href="'.$link.$pages.'">'.$nav['last'].'</a>'; }  
	if( $page < $pages ){ $out .= '<a href="'.$link.( $page + 1 ).'">'.$nav['next'].'</a>'; } 
	return '<div class="paginate" style="text-align:'.$a.';">'.trim( $out ).'</div>'; 
}

Using it … it uses &page= in the address bar to track where you are.


// setup all the data ahead of time

$total = mysql_fetch_row( mysql_query( "SELECT count(*) FROM `table`" ) ); 
$total = $total[0] or 0; 

$p = array(); 
$p['limit']  = 10; 
$p['total']  = $total; 
$p['page']   = ( isset( $_GET['page'] ) ) ? trim( $_GET['page'] ) : 1;  
$p['offset'] = ( $p['limit'] * ( $p['page'] - 1 ) ); 
$p['link']   = '/index.php?page='; 

// this is where you would run you query to show all the rows 
// we can use $p['offset'] and $p['limit'] in the query LIMIT 
// then show your page numbers at the bottom .. 

echo paginate( $p, 'center' ); 


Styling it…


.paginate { margin:16px 0 0 0; padding:0; text-align:left; }  
.paginate * 
{ 
	display:inline-block; margin:0 1px 0 1px; padding:10px; 
	font-family:"Courier New", Courier, monospace; 
	font-style:normal; font-weight:bold; font-size:12px; line-height:normal; text-decoration:none;
	background-color:#222b34; border-radius:8px; -webkit-border-radius:8px; -moz-border-radius:8px; 
}