복붙노트

간단한 PHP 페이지 매김 스크립트 [닫힌]

PHP

간단한 PHP 페이지 매김 스크립트 [닫힌]

데이터베이스에서 오는 데이터 행이 있습니다. 간단한 페이지 매김을 사용하여 테이블을 만들고 싶습니다. 가장 쉬운 방법은 무엇입니까? 누구든지 제공 할 수 있다면 기쁠 것입니다.

해결법

  1. ==============================

    1.이것은 HTML과 코드가 혼합 된 것이지만, 이해하기 쉽고 매우 기본적이고 생각하기에 당신의 필요에 맞게 쉽게 분리되어야합니다.

    이것은 HTML과 코드가 혼합 된 것이지만, 이해하기 쉽고 매우 기본적이고 생각하기에 당신의 필요에 맞게 쉽게 분리되어야합니다.

    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) ? '<a href="?page=1" title="First page">&laquo;</a> <a href="?page=' . ($page - 1) . '" title="Previous page">&lsaquo;</a>' : '<span class="disabled">&laquo;</span> <span class="disabled">&lsaquo;</span>';
    
        // The "forward" link
        $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">&rsaquo;</a> <a href="?page=' . $pages . '" title="Last page">&raquo;</a>' : '<span class="disabled">&rsaquo;</span> <span class="disabled">&raquo;</span>';
    
        // Display the paging information
        echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
    
        // 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 '<p>', $row['name'], '</p>';
            }
    
        } else {
            echo '<p>No results could be displayed.</p>';
        }
    
    } catch (Exception $e) {
        echo '<p>', $e->getMessage(), '</p>';
    }
    
  2. ==============================

    2.내가 이해하기 쉬운 일부 자습서는 다음과 같습니다.

    내가 이해하기 쉬운 일부 자습서는 다음과 같습니다.

    스크립트 :      // 테이블에있는 행의 수를 확인합니다. $ sql = "숫자 (*)에서 숫자 선택"; $ result = mysql_query ($ sql, $ conn) 또는 trigger_error ( "SQL", E_USER_ERROR); $ r = mysql_fetch_row ($ result); $ numrows = $ r [0]; // 페이지 당 표시 할 행 수 $ rowsperpage = 10; // 총 페이지를 찾습니다. $ totalpages = ceil ($ numrows / $ rowsperpage); // 현재 페이지를 가져 오거나 기본값을 설정합니다. if (isset ($ _ GET [ 'currentpage']) && is_numeric ($ _ GET [ 'currentpage'])) {    // var를 int로 변환합니다.    $ currentpage = (int) $ _GET [ 'currentpage']; } else {    // 기본 페이지 번호    $ currentpage = 1; } // end if // 현재 페이지가 총 페이지보다 큰 경우 ... if ($ currentpage> $ totalpages) {    // 현재 페이지를 마지막 페이지로 설정합니다.    $ currentpage = $ totalpages; } // end if // 현재 페이지가 첫 페이지보다 작은 경우 ... if ($ currentpage <1) {    // 현재 페이지를 첫 번째 페이지로 설정합니다.    $ currentpage = 1; } // end if // 현재 페이지를 기준으로 목록의 오프셋 $ offset = ($ currentpage - 1) * $ rowsperpage; // db로부터 정보를 얻는다. $ sql = "SELECT id, FROM numbers LIMIT $ offset, $ rowsperpage"; $ result = mysql_query ($ sql, $ conn) 또는 trigger_error ( "SQL", E_USER_ERROR); // 페치 할 행이있는 동안 ... while ($ list = mysql_fetch_assoc ($ result)) {    // 에코 데이터    echo $ list [ 'id']. ":". $ list [ 'number']. "
    "; } // end while while / ****** 페이지 매김 링크를 만드십시오 ****** / // 표시 할 num 링크의 범위 $ range = 3; // 페이지 1에 없으면 링크를 다시 표시하지 않습니다. if ($ currentpage> 1) {    // show << 링크를 클릭하면 1 페이지로 돌아갑니다.    echo " <<< / a>";    // 이전 페이지를 가져옵니다. num    $ prevpage = $ currentpage - 1;    // 1 개의 페이지로 돌아 가기 << / a>"; } // end if // 현재 페이지 주위의 페이지 범위에 대한 링크를 표시하는 루프 for ($ x = ($ currentpage - $ range); $ x <(($ currentpage + $ range) + 1); $ x ++) {    // 유효한 페이지 번호 인 경우 ...    if (($ x> 0) && ($ x <= $ totalpages)) {       // 현재 페이지에 있다면 ...       if ($ x == $ currentpage) {          // '강조'하지만 링크를 만들지 마라.          echo "[ $ ]";       // 현재 페이지가 아닌 경우 ...       } else {          // 링크로 만듭니다.          echo " $ x ";       } // end else    } // end if } // end for // 마지막 페이지에 없으면 앞으로 및 마지막 페이지 링크 표시 if ($ currentpage! = $ totalpages) {    // 다음 페이지로 이동    $ nextpage = $ currentpage + 1;     // 다음 페이지에 대한 순방향 링크를 echo한다.    echo "> ";    // lastpage에 대한 순방향 링크를 echo한다.    echo " >> "; } // end if / ****** 마 지막 링크 만들기 ****** / ?> http://www.tonymarston.net/php-mysql/pagination.html 이 튜토리얼은 한 번에 전체 로트 대신 많은 수의 데이터베이스 행을 관리 할 수있는 청크로 단계적으로 수행 할 수있는 기능을 사용자에게 제공하려는 개발자를위한 것입니다.

  3. ==============================

    3.

     <?php
    // Custom PHP MySQL Pagination Tutorial and Script
    // You have to put your mysql connection data and alter the SQL queries(both queries)
    
    mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
    mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
    //////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
    $sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
    //////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
    $nr = mysql_num_rows($sql); // Get total of Num rows from the database query
    if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
        $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
        //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
    } else { // If the pn URL variable is not present force it to be value of page number 1
        $pn = 1;
    }
    //This is where we set how many database items to show on each page
    $itemsPerPage = 10;
    // Get the value of the last page in the pagination result set
    $lastPage = ceil($nr / $itemsPerPage);
    // Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
    if ($pn < 1) { // If it is less than 1
        $pn = 1; // force if to be 1
    } else if ($pn > $lastPage) { // if it is greater than $lastpage
        $pn = $lastPage; // force it to be $lastpage's value
    }
    // This creates the numbers to click in between the next and back buttons
    // This section is explained well in the video that accompanies this script
    $centerPages = "";
    $sub1 = $pn - 1;
    $sub2 = $pn - 2;
    $add1 = $pn + 1;
    $add2 = $pn + 2;
    if ($pn == 1) {
        $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    } else if ($pn == $lastPage) {
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
        $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    } else if ($pn > 2 && $pn < ($lastPage - 1)) {
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
        $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
    } else if ($pn > 1 && $pn < $lastPage) {
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
        $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    }
    // This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
    $limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
    // Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
    // $sql2 is what we will use to fuel our while loop statement below
    $sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
    //////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
    $paginationDisplay = ""; // Initialize the pagination output variable
    // This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
    if ($lastPage != "1"){
        // This shows the user what page they are on, and the total number of pages
        $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
        // If we are not on page 1 we can place the Back button
        if ($pn != 1) {
            $previous = $pn - 1;
            $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
        }
        // Lay in the clickable numbers display here between the Back and Next links
        $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
        // If we are not on the very last page we can place the Next button
        if ($pn != $lastPage) {
            $nextPage = $pn + 1;
            $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
        }
    }
    ///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
    // Build the Output Section Here
    $outputList = '';
    while($row = mysql_fetch_array($sql2)){
    
        $id = $row["id"];
        $firstname = $row["firstname"];
        $country = $row["country"];
    
        $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';
    
    } // close while loop
    ?>
    <html>
    <head>
    <title>Simple Pagination</title>
    </head>
    <body>
       <div style="margin-left:64px; margin-right:64px;">
         <h2>Total Items: <?php echo $nr; ?></h2>
       </div>
          <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
          <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
          <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
    </body>
    </html> 
    
  4. from https://stackoverflow.com/questions/3705318/simple-php-pagination-script by cc-by-sa and MIT license