PHP Pagination | Set 1

20 Mar, 2018
PHP is mostly used to store and show data from a database according to the user’s requirements. For example, let us think that we have organized a competition and now have the challenge to show the leaderboard. Our event was very successful and had a participation of over Ten Thousand. Now if we have to show the whole list on one page, the page will be very long so it may not be the best of ways to show a list. What we can do is to distribute the whole list in a number of pages. This method of distributing a single list in a number of pages is known as Pagination. Let us now look at the Advantages and Disadvantages of Pagination.
Disadvantages of Pagination
Let us think of an event where external viewers are significantly low, thus if you publish a leaderboard it is possible that the few users participating will like to keep track of the leaderboard but not the whole leaderboard. A user will tend to see its own rank and the performance of the top rank holder. Thus if we distribute the leaderboard in several pages then we must provide a special way so that the user may navigate to the page where its username is present in the rank list. This seems a bit too much to add in many cases and thus Pagination can be ignored in such cases.
Pagination is pure overhead i.e. Pagination is an additional feature that can be implemented in a cost of extraneous Markup, Styling as well as logic. Thus having a small dataset containing hundreds of records it’s often ignored to use Pagination.
Advantages of Pagination
In one of the disadvantages we got to know that Pagination itself is an overhead, but Pagination can also save us from loading a lot of information at once. For example, let us think of a gallery web-page that should show a big list of images, Now showing thousands of pictures in a single page will require thousands of HTTP requests which will make the page highly unresponsive whereas using Pagination we can show a limited amount of images in a page thus limiting the HTTP requests and moreover creating a more efficient page.
It is always better to use Pagination for medium to large-scale projects because Pagination not only makes the webpage work faster and efficiently but also appears to be much more precise and professional.
Implementing Pagination
Now in order to implement pagination, we first need a big data-set to which we will apply the pagination. For the simplicity of this mini-project, we will use Bootstrap and minimal explicit styling. Seeing the success of the previous competition ProGeek Cup 1.0, we will consider making the leader-board of ProGeek Cup 2.0, so let us start by creating the markup first.We will try to keep the whole page as simple as possible containing a Title, a brief description, and the leader-board table itself.
The Markup
Before starting with the fetch and show cycle of PHP let us first set up the basic interface of the table. After creating a folder in the “WWW” folder/ “htdocs” folder and creating an “index.php” file, I used the following markup to get a basic table interface as shown below.
<!DOCTYPE html><html>  <head>    <title>ProGeeks Cup 2.0</title>    <link rel="stylesheet"     href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/                                     css/bootstrap.min.css">  </head>  <body>    <div class="container">      <br>      <div>        <h1>ProGeeks Cup 2.0</h1>        <p>This page is just for demonstration of Basic            Pagination using PHP.        </p>        <table class="table table-striped table-condensed                                           table-bordered">          <thead>            <tr>              <th width="10%">Rank</th>              <th>Name</th>              <th>College</th>              <th>Score</th>            </tr>          </thead>          <tbody>          </tbody>        </table>      </div>    </div>  </body></html>
Refer to the following article for more detailed description of using table in Bootstrap. Now that we have managed to develop the basic markup we must then get ready with our data.
The Data
If we want to use pagination we must have quite a good amount of data to distribute among pages. Now you may search for sample datasets or create your own. Now for simplicity, I used the following python script to create a fake rank list to be shown on the webpage. By using the random library the data generated is less obvious and using CSV format it can be directly imported into MySQL.
import csv, randomfirstNames = ["Anuran", "Bappa", "Deep", "Dhanraj",               "Harsh", "Sabyasachi", "Saptarshi",               "Sayan", "Shubham", "Sampriti", "Susmita",               "Pronab", "Vaskar", "Sanjeeb", "Anirudh"]lastNames = ["Pandit", "Das", "Bhattacharjee", "Rathi",              "Agarwal", "Mishra", "Garg", "Pal", "Khan",              "Ganguly", "Dutta", "Mukherjee", "Lodhi",              "Malhotra", "Gupta"]collegeNames = ["IIT Delhi", "IIT Kharagpur", "BIT Mesra",                "JIT", "Jadavpur University", "IIT Roorkee",                 "KGEC", "SMIT", "EIEM", "CGEC", "JGEC",                 "IISC Bangalore", "IIIT Allahabad",                 "IIT Kanpur", "IIT BHU"]dataTemplate = [['Rank', 'Name', 'College', 'Score']]   Rank, maxScore = 1, 3000for x in xrange(1500):    i = random.randint(0, 14)    j = random.randint(0, 14)    k = random.randint(0, 14)    entry = [str(Rank), firstNames[i]+" "+lastNames[j],                         collegeNames[k], str(maxScore)]    dataTemplate.append(entry)    maxScore-= random.randint(1, 3)    Rank+= 1    targetFile = open('pagination.csv', 'w')with targetFile:    writer = csv.writer(targetFile)    writer.writerows(dataTemplate)   print "Done" 
In the code above we have taken three lists of first names, last names, and college names. Our motive is to make a fake rank list. We will iterate for 1500 times, each time we will generate three random indices to get a random first name a random last name and a college. We will also generate a fourth random integer that will denote the difference in the score from the previous rank holder’s. Now that we have the CSV file we will go to “phpmyadmin” and import the file to create a new table. The following is the figure explaining the whole procedure and the result.
Now that we have set up our Database as well as done our mark up, we basically have our backbone ready and only need to jump into the PHP part itself. Judging the length of this article, it will be better if we start off in the next article that will be totally focused on implementing a basic pagination system.
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React