Sep
10
Here’s a simple way to handle pagination that uses MySQL’s FOUND_ROWS() function and mysqli::multi_query()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <?php $page = isset($_GET['page']) ? (int) $_GET['page']: 1; $size = 10; $offset = ($page - 1) * $size; $db = new mysqli("localhost", "drew", "mypass", "db"); $sql = "SELECT SQL_CALC_FOUND_ROWS username FROM user LIMIT $offset, $size;" . "SELECT FOUND_ROWS()"; $users = array(); $total = 0; if ($db->multi_query($sql) && $res = $db->store_result()) { // fetch this page of user records while (list($name) = $res->fetch_row()) { $users[] = $name; } // fetch the TOTAL number of users $db->next_result(); list($total) = $db->store_result()->fetch_row(); } $pages = ceil($total/$size); echo "Total Users: $total<br>"; echo "Total Pages: $pages<br>"; echo "Current Page: $page<br><br>"; foreach ($users as $u) echo "$u<br>"; if ($page > 1) echo '<a href="?page=', $page-1, '">« Prev</a>'; if ($page > 1 && $page < $pages) echo " | "; if ($page < $pages) echo '<a href="?page=', $page+1, '">Next »</a>'; ?> |
See Also: MySQLI SELECT, MySQLI INSERT, MySQLI UPDATE, MySQLI DELETE