0

I am trying to work on my site and get "pagination" to work with it. I got so far as to make it loop out some of the stuff I want from my database but what I do not understand or get to work is the "next" & Previous" page. How can I in the code I did switch from page 1 to 2 and back to 1 etc.?

echo '<div id="block" border="1" width="200" style="float:center">';

$i = 0;
$perpage = 10;
$currentpage = 0;

$sql = "SELECT * FROM dogs";
$numRows = mysql_num_rows(mysql_query($sql));
$lastpage = ceil($numRows / $perpage);
$getquery = mysql_query("$sql ORDER by ID LIMIT $currentpage, $perpage");

while($rows = mysql_fetch_assoc($getquery)){

    $id=$rows['id'];
    echo '<a href="/index.php?dogs='. $id .'">
        <img src="/dogs/'. $id .'.jpg" width="100" height="100"  alt="" />
    </a>';

    $i++;

    if($i == 10) {
        echo '<br />';
        echo '<br />';
        $i = 0;
    }
}
echo '</div>';
Rohit
  • 403
  • 3
  • 15
Rizzzler
  • 193
  • 2
  • 12
  • Well, you compute an 'offset' and a 'limit' value based on the `$perpage` and `$currentpage` and enhance your sql query with those two parameters. Then for every request for a certain page you have your entries. – arkascha Feb 26 '14 at 09:04
  • I tried some examples and i did not get it to work hencei asked here, do you think you can help och give an example? :/ – Rizzzler Feb 26 '14 at 09:09
  • In your script above `$currentpage` is hard coded to 0. Instead it must be a request parameter indicating _which_ page you want to show. – arkascha Feb 26 '14 at 09:13

1 Answers1

0

the LIMIT clause is not correct, it should get an offset, and not a page number. the offset should be:

(pageSize * currentPage) - pageSize

You also need a second query to calculate the total number of items, and derive the total number of pages from that:

ceil(totalItemCount / pageSize); // ceil() rounds to top

with these 2 numbers, you can then build your pagination controls.

Also, this question has been asked multiple times already, so search SO for some guidance: Simple PHP Pagination script

Community
  • 1
  • 1
NDM
  • 6,731
  • 3
  • 39
  • 52