Monday, April 15, 2013

pagination using PHP and JavaScript for a report

We can use limit in MySQl query to divide query into pages. But here I try to use CSS display to hide or show pages.
First we define each number in page as a box and hover effect. And define class current to hightlight current page
div.paging li a {
    text-decoration: none;
    padding: 2px 5px;
   border: 1px solid #000;
div.paging li a:hover{
   color: #ececec;
   background: #366161;
div.paging li a.current {
   color: #ececec;
   font-style: italic;
   background: #00283e;

Assume we already have a nig array $event in PHP, we can set results peg page
     $results_per_page = 15;
     $num_pages = max(ceil($num_results/$results_per_page), 1);

We create a JavaScript function setPage_r to only display current page and highlight current page number
 <script type="text/javascript">
 function setPage_r(num,num_pages){
     for(var i=1; i<=num_pages; i++){
        document.getElementById('page-'+i).style.display = "none";
         document.getElementById('page-mark-top-'+i).className = " ";
        if(i==num) {
           document.getElementById('page-'+i).style.display = "block";
           document.getElementById('page-mark-top-'+i).className = "current";

To display pages. If more than 20 pages, we go to next line
<div class="paging"><span>Page #</span>
    for($i=1; $i<=$num_pages;$i++){
    echo '</ul></div></div><div class="clear-after"> <div class="paging"><span>Page #</span><ul>';?>
        <li><a href="#<?php echo ($i); ?>" id="page-mark-top-<?php echo ($i); ?>"  onclick='setPage_r(<?php echo $i.",$num_pages"; ?>);return false;'><?php echo $i; ?></a>
    <?php } ?>

Table body:
   $row_count = 0;

 foreach($events as $group_id=>$group_events){
          $this_count ++;
          $end_div =0;
            if($j==1) echo "<div id='page-$j'>   <table   cellspacing=0 border=1 style='font-size:10' width=100% >";
             else echo "</table></div><div id='page-$j'><table   cellspacing=0 border=1 style='font-size:10' width=100% >";
      <!-- <th scope="col"><a href="#program_name" onclick="setSort('program_name')">Member Name</a></th> -->
      <!-- <th scope="col"><a href="#last_name" onclick="setSort('contact_last_name')">Society</a></th> -->
      <th scope="col" width=35% style="text-align:left" >Name of Course</th>
      <th scope="col"  style="text-align:left" >Date of Course</th>


         echo '<td>'.$event['header'].'</td>';
         echo '<td>'.$event['dates'].'</td>';
           echo '<td></tr>';


Final, we set the default page is the first page:
 setPage_r(1,<?php echo $num_pages; ?>);

No comments:

Post a Comment