Chose Language:
comments
Author: Admin/Publisher |finished | checked

PHP pagination

It was time to address the topic of pagination in PHP; This post will focus more on covering the fundamentals of how pagination is done in a programming language, and, of course, the language we will use is PHP.

If you are very new to the internet, you may wonder, what do we mean by pagination on a website?

Pagination is a way of displaying the results of a search or information on multiple pages.

Let’s start

Let’s start with an array.

Array de nombres
$nombres_completos = [
"Juan Pérez",
"María Rodríguez",
"Luis García",
"Ana Martínez",
"Carlos López",
"Laura González",
"Pedro Sánchez",
"Isabel Fernández",
"Miguel Torres",
"Sofía Ramírez",
"Diego Morales",
"Elena Ruiz",
"Andrés Castro",
"Carmen Vargas",
"Alejandro Herrera",
"Raquel Ortega",
"Javier Cruz",
"Valentina Paredes",
"José Ramón Mendoza",
"Patricia Jiménez",
"Felipe Aguilar",
"Lucía Castro",
"Roberto Medina",
"Adriana Silva",
"Daniel Molina",
"Natalia Pérez",
"Manuel López",
"Carolina Ruiz",
"Héctor Torres",
"Rocío Soto",
"Fernando Navarro",
"Isabella Gómez",
"Antonio González",
"Alicia Ríos",
"Gustavo Romero",
"Catalina Herrera",
"Pablo Fernández",
"Valeria López",
"Ricardo Díaz",
"Gabriela Morales",
"José Luis Martínez",
"Paula García",
"Juan Carlos Ramírez",
"Marina Ortiz",
"Roberto Vargas",
"Camila Castro",
"Ernesto Pérez",
"Diana Torres",
"Andrés Medina",
"Alejandra Sánchez"
];

This array, if I remember correctly, has 50 random names.

How could I display 5 names per page? We could do something like the following using the PHP array_chunk function.

$data_per_page = 5;
$narray = array_chunk($nombres_completos,$data_per_page);

Now we have arrays of 5 elements per page, resulting in 10 pages where the information will be displayed.

After this, How would I number these 10 pages?

$page_num = 0;
for ($n = 0; $n < count($narray) ; $n++){
	$page_num = $page_num + 1;
	echo $page_num;
}

Now we would have page numbering from 1 to 10.

Continuing with our pagination, What else would we need? We would need to know which page we are currently on. Here, it can be a bit confusing because we are using array_chunk, and thus, we are dealing with arrays nested within our $narray.

My first page is 1, so to iterate through my first array, I should do this:

$actual_page=1;
foreach ($narray[$actual_page -1] as $element) {
	echo "<p>$element</p>";
}

Using $_GET on pagination

Something we have to consider is that our current page won't always be 1; therefore, we need to handle that. One approach is to use $_GET with isset.

if (isset($_GET["page"])) {
	$actual_page =$_GET["page"];
}


This way, if we visit http://localhost/tutorialphp/pagination/?page=3, we will get the data for page 3.

Setting the links

Now, all that's left is to make sure our pagination includes the links:

for ($n = 0; $n < count($narray) ; $n++) {
	$page_num = $page_num + 1;
	$link = "/tutorialphp/pagination/?page=".$page_num;
	echo "<a href=$link>".$page_num."</a>";
}

Let's keep in mind that I'm not using a virtual host to make it similar to a project in production. Consequently, The link's path is based on the directory structure of where I'm creating this tutorial for those who want to read it.

If you want to test the code, you should adjust it according to the path on your own computer.

Why are we using array_chunk?

We are using array_chunk because it's a very good tool for controlling how much data we return. If you're wondering why we're not using an SQL query with a limit, you're also right. We need to control how much data we fetch.

But what if we have many users, let's say 1,000,000 at the same time, or we're a website for online reading or streaming movies, etc., with a very large flow of users navigating through pages?

In my opinion, we shouldn't be querying the database for every page, but rather fetching a relevant amount of data in the query and then processing it with array_chunk.

PHP Pagination with SQL

Let's see if you remember some of what we discussed earlier. For this exercise, we'll create a table in a database with enough data.

First create a database in your XAMPP, WAMP, or local server.

Add the following table by running the SQL code in the SQL tab:

Este script SQL crea una tabla usuarios en una base de datos seleccionada y la llena
CREATE TABLE usuarios (
id INT AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(50),
apellido VARCHAR(50),
email VARCHAR(100)
);
INSERT INTO usuarios (nombre, apellido, email) VALUES
("Abby Reichel","Klein","connelly.tania@rippin.info"),
("Vinnie Shields MD","McGlynn","helen.thompson@oconner.com"),
("Toy Rau","Lueilwitz","jstiedemann@hartmann.org"),
("Marge Mohr","Gleason","shields.molly@gmail.com"),
("Devin Sanford","McClure","bogisich.susan@langosh.com"),
("Prof. Nico Luettgen IV","Pacocha","zhaley@predovic.com"),
("Ms. Meta Kuvalis I","Cronin","anna.mayer@west.com"),
("Dr. Jerald Maggio","Collins","eveline51@moen.com"),
("Sydnie Hessel","Wehner","carolyn.huel@wyman.com"),
("Josianne Purdy","Altenwerth","klein.tiara@orn.info"),
("Mrs. Kacie Harvey","Raynor","conn.dorothy@kiehn.com"),
("Eduardo Steuber","Kirlin","verna.hackett@homenick.com"),
("Arnaldo Wyman","Funk","gibson.kaylee@gmail.com"),
("Marco Russel DDS","Crist","celestino.bauch@hotmail.com"),
("Alexanne Bins","Tremblay","fnitzsche@gmail.com"),
("Ayana Hintz","Bergnaum","lorine.miller@muller.biz"),
("Amara Strosin I","Hahn","bstamm@aufderhar.biz"),
("Mrs. Abbey Gulgowski Sr.","Reichel","mgreenholt@gmail.com"),
("Kaden Cormier","Cruickshank","eturner@gmail.com"),
("Stacey Gutmann","Gutkowski","zoe85@gmail.com"),
("Asha Lakin","Green","hilma.eichmann@gmail.com"),
("Prof. Hal Beier","Funk","filiberto.torp@gmail.com"),
("Prof. Sterling Pacocha I","Keeling","qjenkins@gmail.com"),
("Reggie Reichert","Stehr","schmidt.marlene@gmail.com"),
("Elody Stracke","Kihn","pemard@gmail.com"),
("Aniyah Roberts DDS","Wiegand","juliet18@feest.com"),
("Maia Miller","Cronin","abernathy.stanton@gmail.com"),
("Davonte Hegmann","Bechtelar","kennith.abernathy@yahoo.com"),
("Vince Hayes II","Romaguera","ralph.hand@yahoo.com"),
("Rogers Kreiger","Stanton","willms.darryl@gmail.com"),
("Maya Waters","Lockman","ephraim.hudson@waters.net"),
("Gerda Wiza","Schinner","scotty.hermann@lehner.info"),
("Brian Fadel","Ullrich","hartmann.dereck@leffler.com"),
("Hattie Stamm","Braun","ugoodwin@west.net"),
("Carlee Maggio Jr.","Mueller","willms.friedrich@yahoo.com"),
("Bell Smitham PhD","Schuster","khessel@gmail.com"),
("Eleonore Emard","Anderson","gerhold.brooklyn@collier.biz"),
("Merlin Buckridge","McKenzie","maggio.candido@kassulke.info"),
("Melyssa Stamm DDS","Spencer","nettie.rohan@yahoo.com"),
("Dr. Corine Trantow MD","Stamm","uyost@gmail.com"),
("Dortha Johnston","Zulauf","leonie.koelpin@schinner.net"),
("Prof. Edmond Mitchell","Kris","thad.koepp@tillman.com"),
("Viviane Strosin","Hettinger","marcus11@rohan.com"),
("Santina Mertz","White","muller.brooke@marvin.biz"),
("Walton Steuber","Runte","emilia.kshlerin@hotmail.com"),
("Alexanne Cronin","Rolfson","murphy.jaron@streich.biz"),
("Otho VonRueden","Kozey","legros.dereck@rolfson.com"),
("Nestor Schoen V","Kilback","mann.sammie@johnson.com"),
("Amie Schmeler","Kris","billie30@nienow.org"),
("Heloise Hansen","Homenick","gusikowski.carlos@yahoo.com"),
("Jerod Nolan","Swaniawski","lemke.eliezer@labadie.com"),
("Pinkie McGlynn V","Hagenes","welch.briana@oreilly.com"),
("Bertrand Kuhn","Wilkinson","obednar@wilderman.biz"),
("Garrick Nader","McLaughlin","hartmann.louie@gmail.com"),
("Dr. Kiley Hickle","Jaskolski","katelyn.reichert@hotmail.com"),
("Gussie Nolan","Armstrong","sean56@yahoo.com"),
("Sister Frami","Beer","darwin.spencer@gmail.com"),
("Mrs. Macie Metz Sr.","Wilkinson","bonita12@yahoo.com"),
("Dr. Tressa Beatty","Kreiger","brennan.ward@yahoo.com"),
("Keaton Moen","O'Conner","carroll.hansen@gmail.com"),
("Dr. Dante Kemmer Sr.","Prosacco","reuben77@hotmail.com"),
("Prof. Maxime Donnelly","Rodriguez","earnest.brown@gmail.com"),
("Antonio Jones DVM","Rutherford","lynch.elmo@stokes.com"),
("Jacky Purdy","Weimann","brain70@reilly.com"),
("Dr. Anne Terry DDS","West","ocrona@yahoo.com"),
("Moses Glover DVM","Smith","auer.zoe@yahoo.com"),
("Prof. Amara Collier III","Gulgowski","runte.richmond@walsh.com"),
("Preston Schimmel II","Klein","josue.reilly@yahoo.com"),
("Jaleel Grimes DDS","Crona","perry.ward@gmail.com"),
("Viviane Runolfsdottir I","Cassin","crona.trisha@stroman.biz"),
("Brooke Walker","Hammes","feeney.idella@yahoo.com"),
("Scottie Gutkowski","Lemke","rasheed25@yahoo.com"),
("Alexys Stiedemann PhD","Hickle","alexanne.williamson@gmail.com"),
("Mr. Rodolfo Dach","Gerlach","sschowalter@mann.com"),
("Gussie Baumbach","Murphy","hassie22@yahoo.com"),
("Roel Walsh","Huels","camren.fritsch@hane.com"),
("Sammy Gulgowski","Cremin","king.gudrun@spencer.biz"),
("Cesar Dooley","Conroy","xwillms@tromp.com"),
("Ms. Ottilie Schaden","Wilderman","alexandre81@smith.com"),
("Una Powlowski MD","Kulas","susan07@yahoo.com"),
("Stephania Wolff","Crona","ulices.ritchie@hudson.info"),
("Creola Kilback","Becker","bmueller@gmail.com"),
("Arnulfo Dietrich","Goyette","ngottlieb@kub.com"),
("Ms. Zaria Zboncak","Rohan","fay.emory@stanton.com"),
("Dr. Litzy Hahn PhD","Rodriguez","pokuneva@jast.com"),
("Otha Corwin","Harber","wisozk.michel@sipes.info"),
("Jamir Connelly","Tromp","rrau@kuhlman.com"),
("Jada Shanahan","Franecki","wuckert.sigrid@pfeffer.org"),
("Prof. Ettie Marvin","Konopelski","elvie94@hotmail.com"),
("Juston Stanton","Rempel","ilene28@gmail.com"),
("Maye Lemke","Block","rippin.brando@schultz.com"),
("Sid Upton","Balistreri","jettie.west@goyette.com"),
("Prof. Destany McGlynn","Pagac","isai62@rogahn.com"),
("Prof. Charley Beer I","Ondricka","zhyatt@larson.biz"),
("Amina Donnelly","Ondricka","lmann@yahoo.com"),
("Rasheed Waelchi","Larson","willy.hagenes@yahoo.com"),
("Oda Lindgren","Abernathy","johnathon.mertz@gmail.com"),
("Bartholome Aufderhar IV","Smith","carroll.angelina@padberg.biz"),
("Dino Herzog","Hintz","chyna31@yahoo.com"),
("Conor Kunde","Hegmann","dagmar.stehr@prohaska.com"),
("Marielle Sipes","Lehner","roy.baumbach@gmail.com"),
("Milford Cremin V","Runolfsson","ymoore@kertzmann.com"),
("Dr. Kendrick Marks","Williamson","clare.prosacco@yahoo.com"),
("Maudie King","Pollich","kub.margaret@gmail.com"),
("Annie Dietrich DVM","Stokes","powlowski.daniela@stehr.net"),
("Kyler Medhurst","Strosin","penelope97@hotmail.com"),
("Jordane Lang","Fay","hoppe.delpha@halvorson.com"),
("Cortez Schuppe","Keeling","dlueilwitz@gmail.com"),
("Celia Hansen","Gaylord","hsauer@runolfsson.com"),
("Jillian Runte","Stoltenberg","dibbert.cathy@yahoo.com"),
("Leta Vandervort","Cartwright","damore.frances@torp.com"),
("Heaven McClure DVM","Durgan","alvis77@kreiger.com"),
("Prof. Gaetano Mohr","Reynolds","danial87@carroll.com"),
("Eve Skiles Jr.","Rowe","walsh.devonte@cummings.net"),
("Prof. Delfina Bernhard III","Jacobi","kjakubowski@yahoo.com"),
("Keyshawn Rosenbaum","Schaden","alvera22@hotmail.com"),
("Carolanne Lehner","McGlynn","misael82@tremblay.com"),
("Garret Ebert","Ortiz","trantow.tevin@hotmail.com"),
("Vern Hessel DVM","Kunde","plebsack@yahoo.com"),
("Aiden Donnelly","Powlowski","christopher79@yahoo.com"),
("Prof. Reese Stark II","Corwin","judson.green@williamson.com"),
("Luis Rosenbaum PhD","Roob","gerlach.zechariah@aufderhar.com"),
("Kamron Littel","Bins","tmiller@yahoo.com"),
("Rollin Stroman","Beer","dayne.mann@gmail.com"),
("Mrs. Christa O'Hara MD","Kulas","veum.marques@hotmail.com"),
("Vita Reinger III","Casper","anya67@gmail.com"),
("Prof. Trevor Swift DVM","Hodkiewicz","hettie91@gmail.com"),
("Mr. Craig Marvin III","Towne","konopelski.vincenza@hotmail.com"),
("Bertrand Crist","Funk","rogahn.javon@yahoo.com"),
("Bella Kassulke","Fisher","ferry.zackery@kozey.com"),
("Candelario Feil IV","Schiller","zauer@howe.org"),
("Toby VonRueden III","Schamberger","blick.alverta@hotmail.com"),
("Ms. Ebony Schulist V","Sauer","frank26@hotmail.com"),
("Dr. Peyton Weissnat","Mann","kwilderman@hotmail.com"),
("Wallace Farrell","Cummings","hickle.eduardo@yahoo.com"),
("Demarcus Jenkins","Hagenes","rudolph22@hotmail.com"),
("Tre Schmeler","Ullrich","oreilly.jonathan@white.com"),
("Dr. Josephine Graham DVM","Harvey","shauck@homenick.com"),
("Dr. Kristopher Hirthe Sr.","Metz","bdicki@bogisich.com"),
("Mr. Everett Carter PhD","Hoeger","hartmann.olen@yost.com"),
("Kaya Gleichner","Morar","olson.magdalena@gmail.com"),
("Dr. Gust Stroman","Lowe","karlie.hermiston@mcdermott.com"),
("Alene Goyette","Gleason","skiles.noemi@hotmail.com"),
("Audra Smith","Hirthe","lehner.nicholaus@gmail.com"),
("Aliya Zieme","Pacocha","lera.bahringer@treutel.com"),
("Kade Nader III","Gorczany","lincoln70@deckow.info"),
("Mafalda Ebert","Parker","padberg.nathaniel@bayer.org"),
("Mrs. Maritza Wilderman","Doyle","qwest@gmail.com"),
("Misty Brakus DVM","Gleichner","elaina20@heidenreich.com"),
("Prof. Fanny Hickle II","Deckow","ohara.joey@gmail.com"),
("Yazmin Vandervort","Nicolas","greenholt.colin@yahoo.com");

This time, we will not use array_chunk. Try to implement it as you would in a typical blog. Use an SQL query with LIMIT to fetch the data you want per page, and make sure the page numbering follows this format:

This allows us to see how pagination works in reality. We'll need to control the number of links in the pagination, typically limiting it to a range of 10 to 20.

[1][2][3][4][5][...][100][101][102][103][104]

If we have 1000 pages to display, it doesn't make sense to show 1000 links below each page. It's more practical to display the next 5 or 3 pages, followed by an ellipsis (...) to indicate that there are more pages, and then the last 5 or 3 pages. If you're unsure about this, visit a movie website, for example, and observe how they handle pagination. Then, come back and try to implement it in your code.

[<][6][7][8][9][...][100][101][102][103][104]

TIPS

Retrieve the number of users with the following SQL query:

select count(*) From usuarios

Divide the number of users by the desired number per page to know the amount of links you need.

You'll have to save the value of the link you're requesting.

Using array_chunk and SQL for pagination

As an exercise, you could also incorporate array_chunk into the equation. This time, you'll need to consider fetching the number of elements from multiple pages, for example, the first 5 and the last 5.

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments