October 28, 2012

Suggestions with pagination

Question by dorin dorin

I’ve a problem with pagination. The php code of pagination query is:

$ <? if (isset($_GET["page"])) { 

    $Page = preg_replace("/[^0-9]/","", $_GET["page"]);
} else {
    $Page = 0;
}
$limit       = 10;
$StartFrom  = $limit * $Page;
$TotalFiles = mysql_num_rows(mysql_query("SELECT * FROM linkuri WHERE `categorie` = 'Afaceri' AND status = 1"));
$TotalPages = floor($TotalFiles / $limit); ?>

And code to display it:

$i = 0; while ($TotalPages >= $i) { echo '<a class="active imgf" style="opacity: 1;margin-bottom:3px; margin-top:3px;" href="afaceri.php?page='.$i.'">'.($i+1).'</a>';$i++;}

The problem is I am trying to make the display as: PAGES: "BACK" 1 2 3 4 5 "NEXT"

Answer by Starx

First I would like to suggest an improvement on your query. To count the total rows use:

SELECT count(*) as `totalpost` FROM linkuri WHERE `categorie` = 'Afaceri' AND status = 1

Then, you are create that pagination by doing something like this:

$totalPost = 50; //Dummy total post
$limit = 10;

$pages = $totalPost / $limit; //Giving 5

//Now we know there are five pages
for($i=1; $i<=$pages; $i++) {
  echo $i; // Better echo something like <a href="link">$i</a>
}

P.S: This is a very basic example

After you get the hang of how to create the pagination effect, check this tutorial

How to paginate with PHP?

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!