Pagination in php

      No Comments on Pagination in php

Pagination in php : this code snippets will generate pagination automatically according to the page opened. This code gets the value of page variable in url using “$_GET[‘page’] and generates pagination.

function generate_pagination($current,$total_pages,$url) generate the pagination. The variables passed to this are the number of the current page, total pages, and the url that is to be set to the list items in pagination.

This function checks for three conditions:

  • $current==1 : checks if the current page is the first one. Then it displays pagination beginning from the first to next five links.
  • $current==$total_pages : checks if the current page is equal to the total pages. If it is, the function prints pagination from five links to last.
  • If both the above fail, the current term is the middle in pagination.
 
 <?php

  function generate_pagination($current,$total_pages,$url)
  {
	 $pagination='';
	if($total_pages > 0 && $total_pages != 1 && $current <= $total_pages)
	{
      $pagination.="<ul class='pagination'>";		
      if($current==1)
	  {
		  $first=$current;
	      $last=$current+3;
          $pagination.="<li class='active'><a href='$url?page=$current'>$current</a></li>";
		  for($i=1;$i<=$last;$i++)
		  {
			  $page=$current+$i;
			  $pagination .="<li><a href='$url?page=$i'>$page</a></li>";
		  }
	  }
	  elseif ($current==$total_pages)
	  {
          $first=$current-4;
	      $last=$current;
		  for($i=$current;$i>$current-4;$i--)
		  {
			 
			  $pagination .="<li><a href='$url?page=$i'>$first</a></li>";
			  $first++;
		  }		  
		  $pagination.="<li class='active'><a href='$url?page=$current'>$current</a></li>";
	  }
	  else
	  {
		  $first=$current-3;
	      $last=$current+3;

		  for($i=$first;$i<$current;$i++)
		  {
			 if($i>0)
			 {
			 $pagination .="<li><a href='$url?page=$i'>$i</a></li>";  
			 }
		  }
		  $pagination.="<li class='active'><a href='$url?page=$current'>$current</a></li>";
		  for($i=$current+1;$i<$last;$i++)
		  {
			 if($i>0)
			 {
			 $pagination .="<li><a href='$url?page=$i'>$i</a></li>";  
			 }
		  }
          		  
	  }
	  
	  
	}
	  $pagination.="</ul>";
	  return $pagination;
	  
  }
  
  $current=$_GET['page'];
  echo generate_pagination($current,6,"url.php");


 ?>

Pagination in php – output

Pagination in php

Summary
Pagination in php
Article Name
Pagination in php
Description
Pagination in php : this code snippets will generate pagination automatically according to the page opened. This code gets the value of page variable in url using "$_GET['page'] and generates pagination.
Author
Publisher Name
Scanfcode
Publisher Logo

Leave a Reply

Your email address will not be published. Required fields are marked *