views:

40

answers:

2

I have a small problem with my PHP pagination, I have 6 records and I display 2 at a time, when I click on next and it displays from 2 to 4 records, that works fine, But to display from 4 to 6 records, that does not work. I am not sure what im doing wrong. Anyone have any ideas ? the problem is to do with the calculation for the Next records to be displayed

<?php
$per_page = 2;
$start = $_GET['start'];
$query = mysql_query("SELECT * FROM Directory");
$record_count = mysql_num_rows($query);
$record_count = round($record_count / $per_page);

if(!$start) {
    $start = 0;
}

$query = mysql_query("SELECT * FROM Directory LIMIT $start,$per_page") or     die(mysql_error());
$row = mysql_num_rows($query);
// Output Records here

// Setup next and previous button variables
$prev = $start - $per_page;
$next = $start + $per_page;

echo '<p> <h4>';
if($prev < 0) {
    echo 'Previous';
} else {
    echo '<a href="directory.php?start='.$prev.'>Previous</a>';
}

echo ' ' . $start . ' of ' . $record_count;

if($next < $record_count) {
    echo ' <a href="directory.php?start='.$next.'>Next</a>';
} else {
    echo ' Next';
}
echo '</h4> </p>';
?>
+1  A: 

It looks like it's a formatting issue. When I look at your source for the URL http://gebsbo.limewebs.com/directory/directory.php?start=1 I see:

<br /><p> <h4>Previous 1 of 4 <a href="directory.php?start=3>Next</a></h4> </p> </body>

It looks like you're missing a quote on the href attribute.

In your code, you want:

echo '<a href="directory.php?start='.$prev.'">Previous</a>';

and

echo ' <a href="directory.php?start='.$next.'">Next</a>';
umop
Thanks, I also changed the Next button coding a bit as well to if($next <= $record_count) {. The problem seems to be now fixed, thank you all for the help!
Gebbo
is whatI would like to say, but if i change the number of records to display to 3 out of 6 then the next button doesnt appear, im going to try if($next - 1 < $record_count){
Gebbo
Updated next code to,if(!($start >= $record_count - $page_per)) { echo ' <a href="directory.php?start='.$next.'">Next</a>'; } else { echo ' Next'; }So it now works to an extent
Gebbo
A: 

use this code for calculating :

$num = 10; // number of items on page
$p = $_GET['page']; // the var that comes from url (for ex: htttp://..../xxx.php?page=3)
$r = mysql_query(" select * from your_table ");

$posts=mysql_num_rows($r); // total posts
$total=(($posts-1)/$num)+1; // toatal pages
$total=intval($total);
$p=intval($p);
if(empty($p) or $p<0 or !isset($p)) $p=1;
if($p>$total) $p=$total;
$start=$p*$num-$num;

// here print the html for pagination (for ex: htttp://...../xxx.php?page=1 .. 2 ...3 .... and so on ...) you can make a for() here

$r = mysql_query(" select * from your_table limit ".$start.", ".$num);
while (....) {
.....
}
Gatman