PHP Paginating template

This template gets a "page" of records from database, and then shows the links to navigate to other pages.

Install:
  • Install PHP Mysql Library
  • Copy paginate.php
  • Modify paginate.php to match your database table

paginate.php
<?php

include_once( 'db.php' );

$recordPerPage = 10;

// Get page index
if ( isset( $_GET[ 's' ] ) && is_numeric( $_GET[ 's' ] ) ) {
    $start = $_GET[ 's' ];
} else {
    $start = 0;
}

// Get total number of pages
if ( isset( $_GET[ 'p' ] ) && is_numeric( $_GET[ 'p' ] ) ) {
    $pages = $_GET[ 'p' ];
} else {
    $sql = sprintf( "SELECT COUNT(site) as count FROM site;" );
    $result = $db->query( $sql );
    $row = $result->fetch_assoc();
    $recordCount = $row[ 'count' ];

    if ( $recordCount > $recordPerPage ) {
        $pages = ceil( $recordCount / $recordPerPage );
    } else {
        $pages = 1;
    }
}

$sql = sprintf( "SELECT * FROM site LIMIT %s, %s;", $start, $recordPerPage );
$result = $db->query( $sql );

echo '<table border="1">';
echo '<tr><th>Site</th></tr>';

$bg = '#cccccc';

while ( $row = $result->fetch_assoc() ) {
    $bg = ( $bg=='#cccccc' ? '#ffffff' : '#cccccc' );
    echo sprintf( '<tr><td bgcolor="%s">%s</td></tr>', $bg, $row[ 'site' ] );
}

echo '</table>';

if ( $pages > 1 ) {
    echo '<p>';
    $currentPage = ( $start/$recordPerPage ) + 1;
    
    if ( $currentPage != 1 ) {
        echo sprintf( '<a href="?s=%s&p=%s">Previous</a> ', ($start - $recordPerPage), $pages );
    }
    
    for ( $i=1; $i<=$pages; $i++ ) {
        if ( $i != $currentPage ) {
            echo sprintf( '<a href="?s=%s&p=%s">%s</a> ', $recordPerPage * ( $i-1 ), $pages, $i );
        } else {
            echo $i . ' ';
        }
    }
    
    if ( $currentPage != $pages ) {
        echo sprintf( '<a href="?s=%s&p=%s">Next</a>', $start + $recordPerPage, $pages );
    }
    
    echo '</p>';
}

No comments:

Post a Comment