logo

PHP ページネーション

PHP は主に、データベースのデータを保存および表示するために使用されます。ページネーションは ajax で実行できますが、ここでは非 ajax で実行します。このチュートリアルでは、 MySQL を使用した PHP のページネーション 。例を挙げてページネーションについて簡単に復習してみましょう -

SQL SELECT クエリが数百万のレコードを返す可能性があります。すべてのレコードを 1 ページに表示するのは得策ではありません。単一ページに多数のレコードのリストがあると、ページの読み込みに非常に時間がかかり、特定のデータを見つけるのにも時間がかかることがあります。これは、ユーザーの心に混乱を引き起こす(引き起こす)可能性があります。したがって、ユーザーの要件に応じて、これらのレコードを複数のページに分割します。

では、これらの大量のレコードをページ数に分散するにはどうすればよいでしょうか? 1 つのリストを複数のページに分散する方法は、 ページネーション 。ページングとは、クエリ結果を単一のページではなく複数のページに表示することを指します。

ページネーションとは何ですか?

ページネーションは、データを 1 つのページに配置するのではなく、複数のページに表示する方法です。ページネーションは、レコードを複数のページに分割するのに役立ち、データをより読みやすく、理解しやすくします。

ページネーションは、PHP 開発者にとって一般的なタスクです。 MySQL は、開発者が以下を使用してページネーションを作成するのに役立ちます。 リミット 句は 2 つの引数を取ります。最初の引数は オフセット そして 2 番目の引数は レコード数 それはデータベースから返されます。

PHP でページネーションの概念を使用する利点と欠点をいくつか見てみましょう -

ページネーションの利点

  • ページネーションは、Web ワークをよりプロフェッショナルなものにするため、大規模なプロジェクトで非常に役立ちます。よりプロフェッショナルになるだけでなく、Web ページの動作がはるかに高速、正確、効率的になります。
  • ページネーションを利用すると、データをさまざまなページに分割することで、ページの読み込み時間を節約できます。一度に多くの情報をロードする手間が省けます。
    例えば ​​- 1,000 個の画像がある Web ページでは、各 Web ページに 50 個の画像がある場合よりも画像の読み込みに時間がかかります。
    つまり、何千もの画像には何千もの HTTP リクエストが必要となり、ページが応答しなくなります。この問題は、LIMIT 句を使用したページネーションを利用してデータ量を制限することで解決されます。
  • ページネーションを使用すると、ユーザー エクスペリエンスと広告収入が向上し、ページの読み込み時間が短縮されます。

ページネーションの欠点

ページネーションには強力な利点がいくつかありますが、それでも多くの開発者はページネーションの使用を避けています。ページネーションにはいくつかの強力な利点がある一方で、次のような欠点もいくつかあります。

  • PHP ではページネーション自体が大きなオーバーヘッドとなり、これがページネーションの欠点の 1 つです。これは、無関係なマークアップ、スタイリング、ロジックを犠牲にして実装できる外部機能であるため、完全にオーバーヘッドです。小規模なデータセットでは、ページネーションの使用が無視されることがよくあります。
  • ページネーションが検索エンジンでのページ ランクの低下を引き起こす可能性があります。これは、ページがホームページから離れていて数回のクリックが必要な場合、通常は高いページ ランクが得られないためです。
  • また、リンクの数、ソーシャルシェア、Web ページに表示される結果の総数、情報が複数のページに分割されている場合にページが受け取るアンカー テキストも制限されます。
ナビゲーション設定の構造を変更することで、ページネーション手法の使用を回避できます。

PHP と MySQL を使用したページネーションの実装

ページネーションを実装するには、ページネーションを適用するための大規模なデータセットが必要です。したがって、最初にデータベースとテーブルを作成する必要があります。その後、テーブルにレコードを指定し、ページネーションを作成するためのコーディングを開始します。そのため、データベースから取得したデータを複数のページに分割できます。

ここでは、ページネーションの例を 2 つ紹介します。最初の例は、CSS を使用しないでページネーションを作成するシンプルで基本的な例ですが、2 番目の例では、CSS とブートストラップを使用して魅力的な方法でページネーションを作成します。両方の出力を確認できます。ページネーションを作成する手順は次のとおりです。

ページネーションを作成する簡単な手順 -

  1. データベースとテーブルを作成します。レコードのリストをテーブルに提供します。
  2. MySQL データベースに接続します。
  3. ページネーション リンクを作成してデータを複数のページに分割し、テーブルの最後に追加します。
  4. データベースからデータを取得し、複数のページに表示します。

以下の手順を 1 つずつ実行して、簡単なページネーションを作成します。

例1

以下のコードは、MySQL データベースを利用して PHP で実行されるページネーションの簡単な例です。データベースから取得したデータを複数のページに分割します。この例では、複数のページに表示されるアルファベットのページネーションを作成します。

データベースの作成

まず、 という名前のデータベースを作成します。 ページネーション 作成した名前とその中にあるテーブル アルファベット 。名前による属性の作成 ID そして アルファベット 、テーブル内のデータを提供します。

PHP ページネーション

データベース接続性

PHP ファイルをデータベースに接続することは必須のタスクです。データベースに保存されているデータをWebページに表示することができます。したがって、Web ページにデータを表示するには、PHP ファイルでデータベースを接続します。

データベース接続コードを同じファイルに記述することも、別のファイルに分けて保存し、必要な PHP ファイルに含めることもできます。データベース接続用のコード -

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

このチュートリアルでは、 ミスクリ 拡大。したがって、すべてのクエリは mysqli 形式に従って記述されます。

xdxdの意味

現在のページ番号を取得する

以下のコードは、ユーザーが現在アクセスしているページ番号を特定します。存在しない場合は、デフォルトでページ番号が 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); 

データを取得してWebページに表示する

以下のコードは、データベースからデータを取得し、それに応じて分割された Web ページに表示するために使用されます。

 $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にページのリンクを表示します

このコードを使用すると、WebページのURLがページごとに変わります。

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

最終コード

次に、すべてのコードを 1 つのファイルにまとめてページネーションを実行します。

ファイル: 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

以下の例は、Web ページの表示をより魅力的にするために HTML とともに CSS を使用したページネーションの別の例です。 CSS は Web ページをよりクリエイティブで魅力的なものにします。一方、MySQL はデータをデータベースに保存します。したがって、ページネーションをよりよく学ぶことができます。

データベース接続を除くコード全体を 1 つのファイルに記述しました。したがって、connection.phpとindex1.phpという2つのファイルを作成します。両方のファイルを次の場所に保存します .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;>

データを取得してWebページに表示する

データセットを作成したので、それを取得してさまざまな Web ページに表示する必要があります。以下のコードは、データベースからデータを取得し、それに応じて分割された Web ページに表示するために使用されます。

データのフェッチ

「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;>