Dynamic web paging and http_build_query

In this tutorial you will learn how to make a simple web paging but efficient. A simple implementation that will simplify your life when creating your web applications.

Content

  • What is content pagination?
  • The parts of a web page
  • How to create a web page step by step
    • 1. Show content without pagination
    • 2. The limit of records to display
    • 3. Total records and number of pages
    • 4. Show the content of the selected page
    • 5. Show the user the page they are on
  • Final: Content Pagination Code
  • Extra: Add paging to GET form
  • File download

What is content pagination?

Since the dynamic content pages They exist so does the pagination of their contents.

A good content pagination It will allow the user to navigate through dynamic pages displaying the minimum amount of data possible, knowing where they are at all times with respect to the rest of the data, as well as getting a global idea of ​​the amount of information that can be displayed.

The parts of a web page

He content pagination It is based on a data flow between the database (through queries) and user interaction. This flow of information is made up of several parts:

  1. A specified number of records to display.
  2. The total number of records available in the database.
  3. The HTML links that lead to different pages possible.
  4. A query to the database that will vary according to the page to visualize.

How to create a web page step by step

The order of the parts that I have mentioned just above is the one that is normally followed in an organized way to create a page of contents. But to learn how to paginate, I am going to explain it to you in a different order that will be easier for you to understand:

1. Show content without pagination

Although it is redundant, let’s start at the beginning. The first thing we do when we want to create a dynamic page is to load the information from our database in our php code, for example for web news:

<?php
$query = "SELECT *
          FROM noticia";
$_DB = new PDOAdmin(); 
$noticias = $_DB->execute($query, 1);
?>

In this script I have loaded all the news from the web with my simplified Database Connection Class. At this point, you could display the content of the news with a simple loop foreach:

<h2>Noticias de la web</h2>
<?php
foreach ( $noticias as $noticia ) {
    echo '<h3>' . $noticia['titulo'] . '</h3>';
}
?>

2. The limit of records to display

After showing all the news from our website, we are going to determine the first part of the pagination: The maximum number of records per page. The number of records to display (in the example news) It is subjective, it will depend on our strategy when composing the pages and what occupies each element shown.

Let’s continue with the proposed example. As the number of news is high, more than one hundred, I have decided to show only fifteen news at a time. So I am going to modify my query so that it only returns fifteen news:

<?php
$query = "SELECT *
          FROM noticia
          LIMIT 15";
$_DB = new PDOAdmin(); 
$noticias = $_DB->execute($query, 1);
?>

with instruction SQL LIMIT I limit the number of results that the query will return.now I have indicated the number of records that I am going to show per page, in the next point we will address how to know the available pages.

As a last piece of information, I will tell you something to take into account and that is that Google has an opinion regarding the pagination of content, and that is that the visualization of the web should be prioritized at the top of it, that is, that a user is nothing more open a web page display most of the page by the browser without doing scroll.

The number of records to show (in the news example) is subjective, it will depend on our strategy when composing the pages and what occupies each displayed element.

3. Total records and number of pages

In order to know how much content we have left without showing or, what is the same, how many pages we have available we must know what is the total number of records of the content that will be displayed on the page. In the example, let’s see how many news I have in total using a query:

<?php
$query2 = "SELECT COUNT(*) as n_noticias
           FROM noticia";
$_DB = new PDOAdmin(); 
$resultado = $_DB->execute($query, 2);
$total_noticias  = $resultado['n_noticias'];

As you can see I have obtained the total of news using the function COUNT .

$paginas = ceil( $total_noticias/15 );
?>

Now that I have the total I am going to calculate the number of total pages using the following operation: The operation is as simple as dividing the total records ($total_news) between the number of records per page. I have rounded up with the php function cell() to not get a decimal number like it could be7.4 pages

.

<?php
for( $i = 0; $i < $paginas; $i++ ){
    $pagina_texto = $i + 1;
    echo '<a href="?pag=' . $i .  '">' . $pagina_texto . '</a>';
}
?>

Now we can show the links to the pages available with HTML and CSS on our website, a simple example: Notice that I have added to the url current the appropriate page information for each button using$_GET .

The page will have the value of the page the user is viewing minus one, since pages will start at zero.

4. Show the content of the selected page Now that the users can select a page among those available

<?php
$pagina = isset($_GET['pag']) ? $_GET['pag'] : 0;

We only have to use the information that the links insert in the url ( $_GET ).

$offset = $pagina * 15;

If the user has clicked on the link of a page, I will use that data, otherwise I will be at the beginning of the content and therefore I must use the value zero (the first element of the first page of content). Now we need to know in which exact record, of those that the query will bring, we must indicate that it starts counting. This concept is defined as follows: The first record, that is, the first piece of news, will have the offset zero, the sixteenth record (which will be the first record of the second page of content) will have the offset

  1. fourteen. In the following list I show you the page offsets for my query of fifteen records:
  2. From register 0 to 14
  3. From registration 15 to 29
  4. From register 30 to 44
  5. From register 45 to 59
  6. From register 60 to 74
  7. Registration 75 to 89

….

  1. If my record limit were, for example, 10 then it would look like this:
  2. From register 0 to 9
  3. From registration 10 to 19
  4. From registration 20 to 29
  5. From register 30 to 39
  6. From register 40 to 49

…. Now we are going to modify the news query so that the fifteen records it returns are exactly from the requested page. For this we use the special sentence OFFSET

$query = "SELECT *
          FROM noticia
          OFFSET $pagina LIMIT 15";

from SQL: With this small modification we indicate to our database management system (MySQL for example) that it must return the records starting at the offset and counting the number of records of the

LIMIT.

5. Show the user the page they are on What are we missing? Wellindicate in the links of the pages which of them is the active one this is as simple as looking at the page variable $page and indicate in HTML a CSS class, for exampleactivate

<?php
for( $i = 0; $i < $paginas; $i++ ){
    $pagina_texto = $i + 1;
    $clase = '';
    if( $pagina == $i )
       $clase = 'active';
    echo '<a href="?pag=' . $i .  '" class="'$clase'" >' . $pagina_texto . '</a>';
}
?>

.

Final: Content Pagination Code

<?php
$_DB = new PDOAdmin(); 
$pagina = isset($_GET['pag']) ? $_GET['pag'] : 0;
$offset = $pagina * 15;
//las 15 noticias de la página
 
$query = "SELECT *
         FROM noticia
         OFFSET $pagina LIMIT 15";
$noticias = $_DB->execute($query, 1);
//total de páginas
$query2 = "SELECT COUNT(*) as n_noticias
           FROM noticia";
$resultado = $_DB->execute($query2, 2);
$total_noticias  = $resultado['n_noticias'];
$paginas = ceil( $total_noticias/15 );
 
//VISTA **********************
foreach ( $noticias as $noticia ) {
   echo '<h3>' . $noticia['titulo'] . '</h3>';
}
//ENLACES HTML DE LA PAGINA
for( $i = 0; $i < $paginas; $i++ ){
    $pagina_texto = $i + 1;
    $clase = '';
    if( $pagina == $i )
       $clase = 'active';
    echo '<a href="?pag=' . $i .  '" class="'$clase'" >' . $pagina_texto . '</a>';
}
?>

Well, we are done, to finish I am going to leave you the complete final code:

Despite the fact that I have programmed all the code online and in a single file, I think that normally the queries and the code that performs the calculations would go in a MODEL file and the links in the VIEW of a web developed in MVC (model view controller).

Extra: Add paging to GET form In this tutorial I have tried to explain a easy way to add pagination to a dynamic content page plain asnews, post or products . But if what you want is add pagination to a GET type form

you will run into the problem of keeping the form information while adding the page.

<?php
$query = $_GET;
for( $i = 0; $i < $paginas; $i++ ){
    $pagina_texto = $i + 1;
    $clase = '';
    if( $pagina == $i )
       $clase = 'active';
    //variable que contiene la página
    $query['pag'] = $i;
    //obtengo el texto que irá después de la url 
    $url_query = http_build_query($query);
    //indico en el enlace la nueva query de la página adecuada
    echo '<a href="?' . $url_query . '" class="'$clase'" >' . $pagina_texto . '</a>';
}
?>

Using the http_build_query() function of PHP 5 and 7 we can manipulate the url query (the GET information). In the following example I am going to manipulate the page of a link without worrying about the information that may be in the GET query of the url:

File download I leave here the files for test quietly with your content page

  • and build from there:

Content paging files

Leave a Reply