logo

PHP 페이지 매김

PHP는 주로 데이터베이스의 데이터를 저장하고 표시하는 데 사용됩니다. 페이지 매김은 ajax로 수행할 수 있지만 여기서는 비-ajax로 수행합니다. 이 튜토리얼에서 우리는 MySQL을 사용한 PHP의 페이지 매김 . 예를 들어 페이지 매김에 대해 간략하게 살펴보겠습니다.

SQL SELECT 쿼리는 수백만 개의 레코드를 다시 반환할 수 있습니다. 한 페이지에 모든 기록을 표시하는 것은 좋지 않습니다. 단일 페이지에 많은 레코드 목록이 있으면 페이지를 로드하는 데 너무 많은 시간이 걸릴 수 있으며 특정 데이터를 찾는 데도 시간이 걸릴 수 있습니다. 이는 사용자의 마음에 혼란을 야기할 수 있습니다. 따라서 사용자 요구 사항에 따라 이러한 기록을 여러 페이지에 나누어 보관하십시오.

그렇다면 이렇게 많은 수의 레코드를 여러 페이지에 분산시키려면 어떻게 해야 할까요? 단일 목록을 여러 페이지에 배포하는 방법을 다음과 같이 알려져 있습니다. 쪽수 매기기 . 페이징이란 단일 페이지가 아닌 여러 페이지에 쿼리 결과를 표시하는 것을 의미합니다.

페이지 매김이란 무엇입니까?

페이지 매김은 데이터를 단일 페이지에 배치하는 대신 여러 페이지에 데이터를 표시하는 방법입니다. 페이지 매김은 레코드를 여러 페이지로 나누는 데 도움이 되며, 이는 데이터를 더 읽기 쉽고 이해하기 쉽게 만듭니다.

페이지 매김은 PHP 개발자의 일반적인 작업입니다. MySQL은 개발자가 다음을 사용하여 페이지 매김을 생성하는 데 도움을 줍니다. 한계 절은 두 개의 인수를 취합니다. 첫 번째 인수는 다음과 같습니다. 오프셋 두 번째 주장은 레코드 수 데이터베이스에서 반환됩니다.

PHP에서 페이지 매김 개념을 사용할 때의 장점과 단점을 살펴보겠습니다.

페이지 매김의 장점

  • 페이지 매김은 웹 작업을 더욱 전문적으로 만들어주기 때문에 대규모 프로젝트에서 매우 유용합니다. 더욱 전문적일 뿐만 아니라 웹페이지 작업을 훨씬 빠르고 정확하며 효율적으로 만듭니다.
  • 페이지 매김을 사용하면 데이터를 여러 페이지에 나누어 페이지 로딩 시간을 절약할 수 있습니다. 한 번에 많은 정보를 로드하지 않아도 됩니다.
    예를 들어 - 1000개의 이미지가 있는 웹페이지는 각 웹페이지에 있는 50개의 이미지보다 이미지를 로드하는 데 더 많은 시간이 걸립니다.
    즉, 수천 개의 이미지에 수천 개의 HTTP 요청이 필요하므로 페이지가 응답하지 않게 됩니다. 이 문제는 LIMIT 절을 사용하여 페이지 매김을 통해 데이터 양을 제한함으로써 해결됩니다.
  • 페이지 매김을 사용하면 사용자 경험과 광고 수익이 향상되고 페이지 로딩 시간이 단축됩니다.

페이지 매김의 단점

페이지 매김에는 몇 가지 강력한 이점이 있지만 여전히 많은 개발자가 이를 사용하지 않습니다. 몇 가지 강력한 장점과 함께 페이지 매김에는 다음과 같은 몇 가지 단점도 있습니다.

우르피 자베드가 누구야?
  • 페이지네이션 자체는 PHP에서 큰 오버헤드이며, 이는 페이지네이션의 단점 중 하나입니다. 불필요한 마크업, 스타일 지정 및 논리 비용으로 구현할 수 있는 외부 기능이므로 완전히 오버헤드입니다. 페이지 매김을 사용하기 위해 종종 무시되는 작은 데이터 세트입니다.
  • 페이지 매김은 페이지가 홈 페이지에서 떨어져 있고 여러 번의 클릭이 필요한 경우 일반적으로 높은 페이지 순위를 얻지 못하기 때문에 검색 엔진에서 낮은 페이지 순위를 유발할 수 있습니다.
  • 또한 웹페이지에 표시되는 링크 수, 소셜 공유, 총 결과 수 및 정보가 여러 페이지에 걸쳐 분할될 때 페이지가 수신하는 앵커 텍스트를 제한합니다.
탐색 설정의 구조를 수정하여 페이지 매김 기술의 사용을 피할 수 있습니다.

PHP 및 MySQL을 사용한 페이지 매김 구현

페이지 매김을 구현하려면 페이지 매김을 적용할 대규모 데이터 세트가 필요합니다. 따라서 먼저 데이터베이스와 테이블을 생성해야 합니다. 그 후 테이블에 레코드를 제공하고 코딩을 시작하여 페이지 매김을 생성합니다. 데이터베이스에서 가져온 데이터를 여러 페이지로 분할할 수 있습니다.

여기서는 페이지네이션의 두 가지 예를 소개하겠습니다. 첫 번째 예는 CSS를 사용하지 않는 간단하고 기본적인 페이지 매김 생성 예이고, 두 번째 예에서는 CSS와 부트스트랩을 사용하여 매력적인 방식으로 페이지 매김을 생성해 보겠습니다. 두 가지 모두에 대한 출력을 볼 수 있습니다. 다음은 페이지 매김 생성을 위한 단계입니다.

페이지 매김을 만드는 간단한 단계 -

  1. 데이터베이스와 테이블을 만듭니다. 테이블에 레코드 목록을 제공하십시오.
  2. MySQL 데이터베이스에 연결합니다.
  3. 여러 페이지의 데이터를 분할하고 테이블 하단에 추가하려면 페이지 매김 링크를 만듭니다.
  4. 데이터베이스에서 데이터를 가져와 여러 페이지에 표시합니다.

아래 단계를 하나씩 수행하여 간단한 페이지 매김을 만듭니다.

실시예 1

아래 코드는 MySQL 데이터베이스의 도움으로 PHP에서 수행되는 페이지 매김의 간단한 예입니다. 데이터베이스에서 가져온 데이터를 여러 페이지로 나눕니다. 이 예에서는 여러 페이지에 표시될 알파벳에 대한 페이지 매김을 생성합니다.

데이터베이스 생성

먼저 다음과 같은 데이터베이스를 생성합니다. 쪽수 매기기 우리가 만든 것과 그 안에 이름이 지정된 테이블이 있습니다. 알파벳 . 이름으로 속성 생성 ID 그리고 알파벳 을 클릭하고 테이블에 데이터를 제공합니다.

PHP 페이지 매김

데이터베이스 연결

PHP 파일을 데이터베이스에 연결하는 것은 필수 작업입니다. 데이터베이스에 저장된 데이터를 웹페이지에 표시할 수 있습니다. 따라서 웹페이지에 데이터를 표시하려면 PHP 파일에 데이터베이스를 연결하세요.

동일한 파일에 데이터베이스 연결 코드를 작성할 수도 있고 다른 파일에 별도로 보관하여 필요한 PHP 파일에 포함할 수도 있습니다. 데이터베이스 연결 코드 -

 $conn = mysqli_connect('localhost', 'root', ''); if (! $conn) { die('Connection failed' . mysqli_connect_error()); } else { mysqli_select_db($conn, 'pagination'); } 

이 튜토리얼에서는 mysqli 확대. 따라서 모든 쿼리는 mysqli 형식에 따라 작성됩니다.

현재 페이지 번호를 가져옵니다

아래 코드는 사용자가 현재 방문하고 있는 페이지 번호를 결정합니다. 존재하지 않는 경우 기본적으로 페이지 번호는 1로 설정됩니다.

 if (!isset ($_GET['page']) ) { $page = 1; } else { $page = $_GET['page']; } 

페이지 매김 공식

페이지 매김을 위해서는 페이지 당 표시할 레코드 수의 제한을 설정해야 합니다. 여기서는 페이지당 결과 제한을 10으로 설정하여 아래와 같이 각 페이지에 표시됩니다.

페이지 1 - A~J(1-10)

페이지 2 - K에서 T까지 (11-20)

3페이지 - U부터 Z까지 (21-26)

 $results_per_page = 10; $page_first_result = ($page-1) * $results_per_page; 

총 페이지 수를 가져옵니다

 $query = 'select *from alphabet'; $result = mysqli_query($conn, $query); $number_of_result = mysqli_num_rows($result); //determine the total number of pages available $number_of_page = ceil ($number_of_result / $results_per_page); 

데이터를 검색하고 웹페이지에 표시

아래 코드는 데이터베이스에서 데이터를 검색하고 그에 따라 나누어진 웹페이지에 표시하는 데 사용됩니다.

 $query = &apos;SELECT *FROM alphabet LIMIT &apos; . $page_first_result . &apos;,&apos; . $results_per_page; $result = mysqli_query($conn, $query); //display the retrieved result on the webpage while ($row = mysqli_fetch_array($result)) { echo $row[&apos;id&apos;] . &apos; &apos; . $row[&apos;alphabet&apos;] . &apos;<br>&apos;; } 

URL에 페이지 링크 표시

이 코드를 사용하면 웹페이지의 URL이 페이지마다 변경됩니다.

 for($page = 1; $page<= $number_of_page; $page++) { echo ' <a href="index2.php?page=" . $page ''>&apos; . $page . &apos;  &apos;; </=>

최종 코드

이제 모든 코드를 단일 파일에 모아서 페이지 매김을 완료합니다.

파일: Index2.php

 Pagination <?php //database connection $conn = mysqli_connect('localhost', 'root', ''); if (! $conn) { die('Connection failed' . mysqli_connect_error()); } else { mysqli_select_db($conn, 'pagination'); } //define total number of results you want per page $results_per_page = 10; //find the total number of results stored in the database $query = 'select *from alphabet'; $result = mysqli_query($conn, $query); $number_of_result = mysqli_num_rows($result); //determine the total number of pages available $number_of_page = ceil ($number_of_result / $results_per_page); //determine which page number visitor is currently on if (!isset ($_GET['page']) ) { $page = 1; } else { $page = $_GET['page']; } //determine the sql LIMIT starting number for the results on the displaying page $page_first_result = ($page-1) * $results_per_page; //retrieve the selected results from database $query = 'SELECT *FROM alphabet LIMIT ' . $page_first_result . ',' . $results_per_page; $result = mysqli_query($conn, $query); //display the retrieved result on the webpage while ($row = mysqli_fetch_array($result)) { echo $row['id'] . ' ' . $row['alphabet'] . '</br>&apos;; } //display the link of the pages in URL for($page = 1; $page<= $number_of_page; $page++) { echo ' <a href="index2.php?page=" . $page ''>&apos; . $page . &apos;  &apos;; } ?&gt; </=>

산출:

위의 페이지 매김 예는 아래 출력을 참조하세요.

PHP 페이지 매김

실시예 2

아래 예는 HTML과 함께 CSS를 사용하여 웹페이지 보기를 더욱 매력적으로 만든 페이지 매김의 또 다른 예입니다. CSS는 웹페이지를 더욱 창의적이고 매력적으로 만듭니다. 반면 MySQL은 데이터를 데이터베이스에 저장합니다. 따라서 페이지 매김을 훨씬 더 잘 배울 수 있습니다.

데이터베이스 연결을 제외하고 전체 코드를 단일 파일에 작성했습니다. 따라서 우리는 Connection.php와 index1.php라는 두 개의 파일을 생성할 것입니다. 두 파일을 모두 저장하십시오. .php 확대. 아래 예에서는 페이지 매김을 더욱 창의적이고 매력적으로 만드는 방법을 배웁니다.

    PHP:데이터베이스 연결을 위해 생성됨PHP:페이지 매김을 위해 생성됨

파일:connection.php

 

파일: index1.php

 Pagination table { border-collapse: collapse; } .inline{ display: inline-block; float: right; margin: 20px 0px; } input, button{ height: 34px; } .pagination { display: inline-block; } .pagination a { font-weight:bold; font-size:18px; color: black; float: left; padding: 8px 16px; text-decoration: none; border:1px solid black; } .pagination a.active { background-color: pink; } .pagination a:hover:not(.active) { background-color: skyblue; } <?php // Import the file where we defined the connection to Database. require_once 'connection.php'; $per_page_record = 4; // Number of entries to show in a page. // Look for a GET variable page if not found default is 1. if (isset($_GET['page'])) { $page = $_GET['page']; } else { $page=1; } $start_from = ($page-1) * $per_page_record; $query = 'SELECT * FROM student LIMIT $start_from, $per_page_record'; $rs_result = mysqli_query ($conn, $query); ?> <br> <p>This page demonstrates the basic Pagination using PHP and MySQL. </p> <table class="table"> <tr> <th>ID</th> <th>Name</th> <th>College</th> <th>Score</th> </tr> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> <?php $query = 'SELECT COUNT(*) FROM student'; $rs_result = mysqli_query($conn, $query); $row = mysqli_fetch_row($rs_result); $total_records = $row[0]; echo '</br>&apos;; // Number of pages required. $total_pages = ceil($total_records / $per_page_record); $pagLink = &apos;&apos;; if($page&gt;=2){ echo &apos;  Prev  &apos;; } for ($i=1; $i<=$total_pages; $i++) { if ($i="=" $page) $paglink .=" &lt;a class = " active' href="index1.php?page=" .$i.''>&apos;.$i.&apos;  &apos;; } else { $pagLink .= &apos;  &apos;.$i.&apos;  &apos;; } }; echo $pagLink; if($page<$total_pages){ echo ' next '; } ?> <input id="page" type="number" min="1" max placeholder required> Go function go2Page() { var page = document.getElementById(&apos;page&apos;).value; page = ((page&gt;)?:((page<1)?1:page)); window.location.href="index1.php?page=" +page; } < pre> <p> <strong>Output:</strong> </p> <p>See the below output for above pagination example -</p> <img src="//techcodeview.com/img/php-tutorial/93/php-pagination-3.webp" alt="PHP Pagination"> <p>Note that code written inside the tag is used for styling and to give an attractive look to the table and pagination present inside the webpage. We also used bootstrap for this.</p> <h3>Explanation of code</h3> <p>Now, we will explain the code used for creating pagination.</p> <h3>Database creation</h3> <p>First of all, create a database named by <strong>pagination</strong> as we created and a table inside it named <strong>student</strong> . Create attribute by name <strong>Rank, Name, College,</strong> and <strong>Score</strong> , and provide at least 25 records in the table.</p> <img src="//techcodeview.com/img/php-tutorial/93/php-pagination-4.webp" alt="PHP Pagination"> <h3>Database Connectivity</h3> <p>Connecting the PHP file to the database is a required task. In this tutorial, we are using <strong>mysqli</strong> extension. So, all the queries are written according to mysqli format.</p> <p>Database connectivity code can be written in the same file or you can also keep it separate into another file and include it to your required PHP file. Code for database connection-</p> <pre> $conn = mysqli_connect(&apos;localhost&apos;, &apos;root&apos;, &apos;&apos;); if (! $conn) { die(&apos;Connection failed&apos; . mysqli_connect_error()); } else { mysqli_select_db($conn, &apos;pagination&apos;); } </pre> <h3>Fetch data and display on webpage</h3> <p>As we have created dataset, now we need to fetch and display it to various webpages. The below code is used to retrieve the data from database and display on the webpages that are divided accordingly.</p> <h3>Fetch data</h3> <p>After establishing the database connection in &apos;connection.php&apos; file, we just need to import it into our code using require_once keyword. We will explicitly define the number of records per page to show.</p> <pre> require_once &apos;connection.php&apos;; $per_page_record = 4; // Number of entries to show in a page. // Look for a GET variable page if not found default is 1. if (isset($_GET[&apos;page&apos;])) { $page = $_GET[&apos;page&apos;]; } else { $page=1; } //determine the sql LIMIT starting number for the results on the displaying page $start_from = ($page-1) * $per_page_record; $query = &apos;SELECT * FROM student LIMIT $start_from, $per_page_record&apos;; $rs_result = mysqli_query ($conn, $query); </pre> <h3>Display data</h3> <p>This section is very simple. In this section, we iterate the loop over the records that we fetched and display each record stored in columns of the table.</p> <pre> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </pre> <h3>Pagination Link creation</h3> <p>Now the most important code is pagination link creation. So, we will create the Previous, Next, and numeric links for pagination and add them to bottom of the table.</p> <pre> if($page&gt;=2) { echo &apos;  Prev  &apos;; } for ($i=1; $i<=$total_pages; $i++) { if ($i="=" $page) $paglink .=" &lt;a class = " active' href="index1.php?page=" .$i.''>&apos;.$i.&apos;  &apos;; } else { $pagLink .= &apos;  &apos;.$i.&apos;  &apos;; } }; echo $pagLink; if($page<$total_pages){ echo ' next '; } < pre> <p>Without using CSS, the pagination will be created same as the screenshot below, which is similar to the example 1.</p> <img src="//techcodeview.com/img/php-tutorial/93/php-pagination-5.webp" alt="PHP Pagination"> <p>After including CSS code into the index1.php file, the pagination will be looked like the screenshot below. In example 1, we have created simple pagination that was logically correct, but visually it is not so good. </p> <img src="//techcodeview.com/img/php-tutorial/93/php-pagination-6.webp" alt="PHP Pagination"> <h3>Code for Random Moment</h3> <p>In case when the number of pages is too much, this code helps us for random moment. By entering the page number in the input field, a user can directly move to that page. This code is written in JavaScript.</p> <pre> function go2Page() { var page = document.getElementById(&apos;page&apos;).value; page = ((page&gt;)?:((page<1)?1:page)); window.location.href="index1.php?page=" +page; } < pre> <p>Apart from all these codes, we have also included bootstrap into index1.php to make the table view good. This code is written inside the tag.</p> <pre> </pre> <hr></1)?1:page));></pre></$total_pages){></=$total_pages;></pre></1)?1:page));></$total_pages){></=$total_pages;>

데이터를 가져와 웹페이지에 표시

데이터세트를 만들었으니 이제 이를 가져와서 다양한 웹페이지에 표시해야 합니다. 아래 코드는 데이터베이스에서 데이터를 검색하고 그에 따라 나누어진 웹페이지에 표시하는 데 사용됩니다.

데이터 가져오기

'connection.php' 파일에서 데이터베이스 연결을 설정한 후 require_once 키워드를 사용하여 코드로 가져오기만 하면 됩니다. 표시할 페이지당 레코드 수를 명시적으로 정의합니다.

 require_once &apos;connection.php&apos;; $per_page_record = 4; // Number of entries to show in a page. // Look for a GET variable page if not found default is 1. if (isset($_GET[&apos;page&apos;])) { $page = $_GET[&apos;page&apos;]; } else { $page=1; } //determine the sql LIMIT starting number for the results on the displaying page $start_from = ($page-1) * $per_page_record; $query = &apos;SELECT * FROM student LIMIT $start_from, $per_page_record&apos;; $rs_result = mysqli_query ($conn, $query); 

데이터 표시

이 섹션은 매우 간단합니다. 이 섹션에서는 가져온 레코드에 대해 루프를 반복하고 테이블 열에 저장된 각 레코드를 표시합니다.

김프 선택 취소 방법
 <tr> <td></td> <td></td> <td></td> <td></td> </tr> 

페이지네이션 링크 생성

이제 가장 중요한 코드는 페이지 매김 링크 생성입니다. 따라서 페이지 매김을 위한 이전, 다음 및 숫자 링크를 생성하고 이를 테이블 하단에 추가하겠습니다.

 if($page&gt;=2) { echo &apos;  Prev  &apos;; } for ($i=1; $i<=$total_pages; $i++) { if ($i="=" $page) $paglink .=" &lt;a class = " active\' href="index1.php?page=" .$i.\'\'>&apos;.$i.&apos;  &apos;; } else { $pagLink .= &apos;  &apos;.$i.&apos;  &apos;; } }; echo $pagLink; if($page<$total_pages){ echo \' next \'; } < pre> <p>Without using CSS, the pagination will be created same as the screenshot below, which is similar to the example 1.</p> <img src="//techcodeview.com/img/php-tutorial/93/php-pagination-5.webp" alt="PHP Pagination"> <p>After including CSS code into the index1.php file, the pagination will be looked like the screenshot below. In example 1, we have created simple pagination that was logically correct, but visually it is not so good. </p> <img src="//techcodeview.com/img/php-tutorial/93/php-pagination-6.webp" alt="PHP Pagination"> <h3>Code for Random Moment</h3> <p>In case when the number of pages is too much, this code helps us for random moment. By entering the page number in the input field, a user can directly move to that page. This code is written in JavaScript.</p> <pre> function go2Page() { var page = document.getElementById(&apos;page&apos;).value; page = ((page&gt;)?:((page<1)?1:page)); window.location.href="index1.php?page=" +page; } < pre> <p>Apart from all these codes, we have also included bootstrap into index1.php to make the table view good. This code is written inside the tag.</p> <pre> </pre> <hr></1)?1:page));></pre></$total_pages){></=$total_pages;>