Thursday, September 13, 2012

PHP MySQL pagination design



When we have many records in MySQL database, we need PHP MySQL pagination design to display MySQL data.

1) First we need to define how many records to display per page, for example 100
  $pageCount =100;
 2)  Use limit to extract MySQL data per page, for first page in MySQL table members
SELECT  * FROM members LIMIT 0,100;
similary, for second page:
SELECT  * FROM members LIMIT 100,100;
For third page 
SELECT  * FROM members LIMIT 200,100;
 

3)Use PHP GET method to obtain the page number in URL, such as
index.php?page=2
for second page

Example code: index.php
   <?php 
//Connect to MySQL server
        $conn = @mysql_connect("localhost","root","") || die("MySQL connection error"); 

//Connect to database test
        @mysql_select_db("test") || die("test database not exsit!"); 
          

//Get data from table members
        $sql = "SELECT * FROM member"; 
        $result = mysql_query($sql) ; 

//Total number of records
        $rowsNum = mysql_num_rows($result);

// Number of records per page is 100 
       $pageCount =100;
        $pageSize = ceil($rowsNum / $pageCount);  ; 
//Get  the page number, default is 1 first page
        $pageno = $_GET["pageno"]; 
        if ($pageno == "") $pageno = 1; 
        $offset = ($pageno -1) * $pageSize; 
     
        $sql .= " limit {$offset},{$pageSize}"; 
        $result = mysql_query($sql); 
    ?> 
    <table width="850" border="0" cellpadding="5" cellspacing="1" bgcolor="#666666"> 
    <?php if($rowsNum) {?> 
    <tr> 
    <td bgcolor="#FFFFFF">ID</td> 
    <td bgcolor="#FFFFFF">User Name</td> 
    </tr> 
    <?php while($row = mysql_fetch_array($result)){ ?> 
    <tr> 
    <td bgcolor="#FFFFFF"><?php  echo $row['id']; ?></td> 
    <td bgcolor="#FFFFFF"><?php echo $row['name']; ?></td> 
    </tr> 
    <?php } ?> 
    <tr> 
    <td colspan="2" bgcolor="#FFFFFF"> 
        <?php 
            if($rowsNum <= $pageSize) 
            { 
            echo "1"; 
            } 
            else  
            { 
                for($i=1;$i<=$pageCount;$i++) 
                echo "<a href=\"{$_SERVER['PHP_SELF']}?pageno={$i}\">{$i}</a>  "; 
            } 
        ?> 
    </td> 
    </tr> 
    <?php } else { ?> 
    <tr> 
    <td bgcolor="#FFFFFF">Sorry, nor record found!</td> 
    </tr> 
    <?php }?> 
    </table>     

No comments:

Post a Comment