Simple pagination in PHP with MySQL
In this article, you will learn how to create Simple pagination in PHP and MySQL. Pagination means retrieving and displaying your information on different pages rather than on a single page. Pagination is important when we have to display large amounts of data on a single page. If you list all the data on the same page, that will create issues such as browser hang, high page loading time, and long vertical scroll. It may also create confusion for readers. So, the best approach is to split the records into chunks and display them on multiple pages.
Here is the PHP pagination example in which we have fetched the data from the database using the latest PDO (PHP Data Object) and written PHP logic to set pagination on the fetched records. All the coding flows are mentioned step by step, which will make it easier to understand and implement.
Database Connection
STEP 1: In the first step, we have written database connection code. For this, we have created a MySQL table ‘students‘ and inserted data into it as shown below. You can either use your existing database or copy and paste the given code into your MySQL database.
CREATE TABLE IF NOT EXISTS `students` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `students` (`id`, `first_name`, `last_name`, `email`) VALUES (1, 'John', 'Smith', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (2, 'Soyam', 'Mithal', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (3, 'Sohn', 'Gaga', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (4, 'Rita', 'Smith', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (5, 'Rohn', 'Mithal', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (6, 'Sayam', 'Mitra', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (7, 'Shyam', 'Mishra', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (8, 'Ryan', 'Mithal', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (9, 'Rohan', 'Soy', This email address is being protected from spambots. You need JavaScript enabled to view it.'), (10, 'Mita', 'Dahl', This email address is being protected from spambots. You need JavaScript enabled to view it.');
Database Configuration File
Next, we have created a PHP file, configuration.php, where we have written database connection code using PHP PDO. It is a lightweight interface for accessing databases and provides a data access abstraction layer for working with databases in PHP. Copy and paste this code in your configuration file. You will have to change the database, hostname, username, and password with your database credentials and name.
configuration.php
// define database related variables $database = 'db'; $host = 'hostname'; $user = 'username'; $pass = 'password'; // try to connect to database $db = new PDO("mysql:dbname=$database>;host=$host>;port=", $user, $pass); if(!$db)< echo "Error in database connection"; > ?>
data.php
STEP 2: In the second step, we created another PHP file named ‘data.php‘. In this page, we have set the data record limit on each page, start counter variable, next counter variable, previous counter variable. Like- on each page, we need to set the record limit to 4, so we have stored this in a variable $per_page. On the first page, the page counter is 0, which is stored in $page_counter. If the user clicks on the next page, this counter increases by one, and if the user clicks on the previous page, this counter decreases by one. We have passed these variables as WHERE clauses to the SELECT statement. So exactly those amounts of data will be fetched from the database that we have to display on the pagination page.
//include configuration file require 'configuration.php'; $start = 0; $per_page = 4; $page_counter = 0; $next = $page_counter + 1; $previous = $page_counter - 1; if(isset($_GET['start']))< $start = $_GET['start']; $page_counter = $_GET['start']; $start = $start * $per_page; $next = $page_counter + 1; $previous = $page_counter - 1; > // query to get messages from messages table $q color: #0000ff;">$start, $per_page"; $query = $db->prepare($q); $query->execute(); if($query->rowCount() > 0)< $result = $query->fetchAll(PDO::FETCH_ASSOC); > // count total number of rows in students table $count_query = "SELECT * FROM students"; $query = $db->prepare($count_query); $query->execute(); $count = $query->rowCount(); // calculate the pagination number by dividing total number of rows with per page. $paginations = ceil($count / $per_page); ?>
index.php
STEP 3: In the third step, we created an ‘index.php‘ file. This is the main file that we will call in the browser. This file contains mostly HTML code to display the records and pagination links with the pagination page numbers.
Простая пагинация на php
Решил описать такой на первый взгляд простой но очень интересный момент в web программирование как пагинация.
Наверное каждый web программист хоть раз да и сталкивался с пагинацией, и понимает что универсального решения нет! По этому я предлагаю посмотреть те простые решения которые сам использую.
p.s. В топике приведен пример пагинации на php, без использования AXAJ и тд. Это сделано для того что б продемонстрировать саму суть, так сказать сделать каркас.
Поехали!
И так начнем. Представим что у нас есть большое количество какого то контента контента (заметки, товары и тд). И вот в один момент мы понимаем что отображать все это на одной странице, неправильно и не хорошо. По этому мы решаем этот контент разбить на части (страницы).
Но для того что б нам это сделать нам нужно знать несколько значений.
- Количество всех страниц.
- Количество отображаемых страниц в пагинации.
- Текущую страницу
Если честно то данных нам нужно немножко больше, но все это зависит от того какую именно пагинацию мы хотим сделать, так что об остальных данных мы поговорим чуть позже.
Допустим количество всех страниц нам известно и оно 45. Текущую страницу мы будем брать с $_GET’а, а если её там нет, то задавать она будет ровна 1.
А вот с количеством отображаемых страниц все интересней, я решил дать нашему скрипту немного гибкости, так что мы могли сами задать количество ссылок с лева и права от текущей странице, выглядит это примерно так:
$iCurr = (empty($_GET[‘page’]) ? 1 : intval($_GET[‘page’]));
/*всего страниц или конечная страница*/
$iLeftLimit = 4;
$iRightLimit = 5;
/*вызов функции*/
makePager($iCurr, $iLastPage, $iLeftLimit, $iRightLimit) ;
Ну вот все данные у нас уже есть и можно заняться самой функцией пагинации.
- текущая страница — $iCurr
- всего страниц или конечная страница — $iLastPage
- левый лимит — $iLeftLimit
- правый лимит- $iRightLimit
Я специально убрал вывод, что б не засорять код, но он мог выглядеть например так:
if($iCurr > $iLeft && $iCurr < ($iEnd-$iRight))
for($i=$iCurr-$iLeft; $i echo ».($i == $iCurr ? ‘‘.$i.’‘ : $i).» ;
>>
Давай посмотрим код поближе.
Первый вариант развития событий, это если наша страница находиться где то в центре (например страница 8), и количество страниц с лева и с права могут свободно отображаться, это самый простой вариант из возможных.
А что же будет если мы находиться например на странице номер 2?
Ведь в условии мы задали что нужно отображать с лева 4 ссылки.
Тогда нам на помощь приходит следующий код:
$iSlice — это количество элементов которые не будут показаны с лева, и которые соотвецтвенно нужно добавить справа, что количество ссылок оставалось постоянным.
Можно было б if’ом запретить вывод страницы если она меньше 1 и больше макс. странице но это б было так не красиво.
Ну и последний вариант, что если мы находимся например на 44 странице, и показать с права 5 мы не можем тк, страниц всего 45?
И код:
else $iSlice = $iRight-($iEnd — $iCurr);
for($i=$iCurr-($iLeft+$iSlice); $i //вывод
>>
P.S.
Еще несколько вариаций на тему:
Если нам не важно что б количество выводимых ссылок было одинаковое то можно 2 и 3 условия заменить такими:
//второе условия:
elseif($iCurr <=$iLeft)
for($i=1; $i //вывод
> >