📜  php代码示例中的分页

📅  最后修改于: 2022-03-11 14:54:20.635000             🧑  作者: Mango

代码示例1
try {

    // Find out how many items are in the table
    $total = $dbh->query('
        SELECT
            COUNT(*)
        FROM
            table
    ')->fetchColumn();

    // How many items to list per page
    $limit = 20;

    // How many pages will there be
    $pages = ceil($total / $limit);

    // What page are we currently on?
    $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
        'options' => array(
            'default'   => 1,
            'min_range' => 1,
        ),
    )));

    // Calculate the offset for the query
    $offset = ($page - 1)  * $limit;

    // Some information to display to the user
    $start = $offset + 1;
    $end = min(($offset + $limit), $total);

    // The "back" link
    $prevlink = ($page > 1) ? '« ' : '« ';

    // The "forward" link
    $nextlink = ($page < $pages) ? ' »' : ' »';

    // Display the paging information
    echo '

', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, '

'; // Prepare the paged query $stmt = $dbh->prepare(' SELECT * FROM table ORDER BY name LIMIT :limit OFFSET :offset '); // Bind the query params $stmt->bindParam(':limit', $limit, PDO::PARAM_INT); $stmt->bindParam(':offset', $offset, PDO::PARAM_INT); $stmt->execute(); // Do we have any results? if ($stmt->rowCount() > 0) { // Define how we want to fetch the results $stmt->setFetchMode(PDO::FETCH_ASSOC); $iterator = new IteratorIterator($stmt); // Display the results foreach ($iterator as $row) { echo '

', $row['name'], '

'; } } else { echo '

No results could be displayed.

'; } } catch (Exception $e) { echo '

', $e->getMessage(), '

'; }