Labels

Friday, April 12, 2013

How to Creating Paging using PHP and MySQL

Its always possible that your SQL SELECT statement query may result into thousand of records.
But its is not good idea to display all the results on one page. So we can divide this result into many pages as per requirement.

Paging means showing your query result in multiple pages instead of just put them all in one long page.

<?php
    $con = mysql_connect("localhost","root","");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
   
    $db_selected = mysql_select_db("tweebd",$con);  // Database name tweebd
?>




<?php
    $per_page = 50;   // per page 50 content you can change your required value
    $page = 1;          // starting page 1
    if (isset($_GET['page']))
        {
            $page = intval($_GET['page']);
            if($page < 1) $page = 1;
        }
    $start_from = ($page - 1) * $per_page;

    $sql=mysql_query("SELECT * FROM `twee_user` WHERE user_cat LIKE 'user' ORDER BY user_name ASC  LIMIT $start_from, $per_page"); // twee_user table name, user catagory fild name user_cat,
   
    while($row=mysql_fetch_array($sql))
        {
            $i++;   
?>

<div><?php echo $i;?> &nbsp; <?php echo $row['user_name'];?></div>

<?php
    }
    $total_rows = mysql_query("SELECT count(*) as 'total' FROM `twee_user`  WHERE user_cat LIKE 'user'");
    $total_rows = mysql_fetch_row($total_rows);

    $total_rows = $total_rows[0];

    $total_pages = $total_rows / $per_page;
    $total_pages = ceil($total_pages); # 19/5 = 3.8 ~=~ 4
?>

<div align='center' class="pagenum">
<?php
    for($i = 1; $i <= $total_pages; ++$i)
        {
            echo "<a href='index.php?link=UserList&page=$i' class='active'>$i</a> &nbsp;&nbsp;";
        }
?>
<style>
.pagenum a{
    border:1px solid;
    background:red;
    padding:5px;
}

</style>
</div>

DOWNLOAD PHP FILES