简体   繁体   中英

PHP PDO pagination foreach

I'm trying to create a pagination for my PDO query. I cant figure it out. I've tried numerous google searches, but nothing that will work for me. [I probably didn't search hard enough. I'm not sure]

This is my code:

$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();

foreach ($nodes2 as $n1) {
echo "text";
}

I want to be able to limit 10 comments per page, and use $_GET['PAGE'] for the page.

Something that I tried

$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);  
$stm2->execute();
$nodes2= $stm2->fetchAll();

$page_of_pagination = 1;
$chunked = array_chunk($nodes2->get_items(), 10); 
foreach ($chunked[$page_of_pagination] as $n1) {
 echo "text";
}

If someone could help out, I appreciate it.

You need to limit the query that you are performing, getting all values from the database and then limiting the result to what you want is a bad design choice because it's highly inefficient.

You need to do this:

$page = (int)$_GET['PAGE']; // to prevent injection attacks or other issues
$rowsPerPage = 10;
$startLimit = ($page - 1) * $rowsPerPage; // -1 because you need to start from 0
$sql2 = "SELECT * FROM comments WHERE shown = '1' ORDER BY ID DESC LIMIT {$startLimit}, {$rowsPerPage}";

What LIMIT does:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants

More information here: http://dev.mysql.com/doc/refman/5.7/en/select.html

Then you can proceed getting the result and showing it.

Edit after comment:

To get all the pages for display you need to know how many pages are there so you need to do a count on that SELECT statement using the same filters, meaning:

SELECT COUNT(*) as count FROM comments WHERE shown = '1'

Store this count in a variable. To get the number of pages you divide the count by the number of rows per page you want to display and round up:

$totalNumberOfPages = ceil($count / $rowsPerPage);

and to display them:

foreach(range(1, $totalNumberOfPages) as $pageNumber) {
    echo '<a href="?page=' . $pageNumber . '">' . $pageNumber . '</a>';
}

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