简体   繁体   中英

PHP Pagination Get Last Page

Basically I am trying to get last page... And well it works sometimes but then say some data is entered in then it gets the wrong page and more data is entered then right page will appear I am pretty sure it has something to do with the $r part. Theres more to it but uh this is the main part. I think I am just using wrong math or functions please help.

$limit = 10;
if($_GET['page'] == 0 OR $_GET['page'] == 1) {
    $offset = 0;
} else {
    $offset = $limit * $_GET['page'] - $limit;
}
$next = $_GET['page'] + 1;
$back = $_GET['page'] - 1;

$stmt = $db->prepare("SELECT * FROM users");
$stmt->execute();
$count = $stmt->rowCount();

if($count < $limit) {
    $last = 1;
}

$r = $count % $limit;
if($r < 5) {
    $last = ceil($count / $limit);
} else {
    if($r >= 5) {
        $last = floor($count / $limit);
    }
}

if($_GET['page'] == 0 or $_GET['page'] == 1) {
    if (0 >= $last) {
        $page = 0;
    }
    if (1 >= $last) {
        $page = 1;
    }
}

First, you're using some very confusing code, which is probably why you're confused and stumbling across odd bugs. For example, 0 >= $last is the same thing as $last <= 0 and 1 >= $last is the same thing as $last <= 1 . So basically your code reads...

if ($last <= 0) {
    $page = 0;
}

if ($last <= 1) {
    $page = 1;
}

Which if you think about this just means that if $last <= 1 then $page will always be 1 . Your conditions aren't eitheror , so both conditions can be met. This hardly makes sense. Especially since $last really shouldn't be expected to be anything other than 1 or more in any given condition ( ie $page will always be 1 )

Also, your logic to floor or ceil $last hardly makes sense. You don't actually want to do either or one or the other depending on the value of $r . You just always want to ceil regardless.

The idea is if you have 10 things or less, and you're placing up to 10 things per page, then you know that you need exactly 1 page. The problem begins when you have 11 things. Now you need 2 pages, because the extra 1 thing still exceeds the limit of 10 per page. So if you really think about this what this means is that the number of pages needed is always going to be congruent to ceil($count / $limit) . You would never floor that number.

Because ceil(16 / 10) == 2 , but according to your logic you would be doing floor(16 / 10) which is actually 1 . But you can't put 16 things on 1 page if the limit per page is 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM