How to create a page numerator?

Asked

Viewed 245 times

4

I am developing a page "News" with several news, and it will be displayed only 9 news per page, above that, should go to page 2 and so on... how do I do this?

Modelo

  • 1

    This is called "paging". What I knew, with "pure HTML" cannot be done. Maybe using languages like PHP, Python or Ruby will help in this paging task.

  • Cool Wallace, I’m beginner in the area... rsrsrs... could you explain to me how this is done?

  • 1

    @Adrianoaquino, you can do this pagination only with HTML, CSS and Javascript, but you will need a web application (C#, Ruby, PHP, Java) to query the contents to be displayed.

  • Where does this data come from? Does it come from a database? Or is it from a static page that you created?

  • I thought to do in HTML, but should be used Mysql with PHP, but I have little practice, I’m still learning, what you suggest?

  • @Adrianoaquino Good morning, if you use php here’s a tip about pagination (it’s very simple and commented): http://www.sergiotoledo.com.br/tutorials/programacao-php/paginacao-php

  • It is important to know the language, so that we even change the TAG of your question. It leads you to think that you are trying to paginate the data only by HTML

  • @Adrianoaquivo, for the client side you can use some puglin, as I am a ferenho defender of the Zurb Foundation, you should see the following link: http://foundation.zurb.com/docs/components/pagination.html

  • @Wallacemaxters, I am using PHP, JS with Mysql... update the tags at your discretion, thanks for the alert.

  • @Rafaelwithoeft, legal links, mto util, vlw!

Show 5 more comments

1 answer

4

let’s do a basic example in PHP:

try{

    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);

    if (!$page) {
        $page = 1; // Se a "page" não existir, o seu valor é 1
    }

    $limit = 9;

    $offset = ($page * $limit) - $limit; // normaliza o offset utilizado no banco

    $pdo = new PDO('...'); // seu dados de conexão aqui

    $stmt = $pdo->prepare('SELECT count(*) as count FROM noticias');


    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    $number_of_pages = ceil($result['count'] / $limit); // calcula o total máximo de páginas, arredondando pra cima :)

    unset($stmt, $result);

    $stmt = $pdo->prepare("SELECT * FROM notiicias LIMIT {$offset}, {$limit}"); // consulta com os limites

    $stmt->execute();

    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);



} catch(Exception $e){

    echo $e->getMessage();
}

Generating links in HTML:

    <?php for($i = 1; $i < $number_of_pages; $i++): ?>
        <a href="?<?php echo http_build_query(array('page' => $i) +  $_GET)"><?php echo $i ?></a>
   <?php endfor ?>

Explaining:

  • filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) is a new way for PHP to handle data coming from the client. That is, we define the variable page will come through the method GET, and should be an integer value. It will be useful to know which current page we are on. By default, see that its value is 1;

  • The calculation of $offset is done as follows. For the user should display the count from 1, however, in SQL, this count should be made from 0. That’s why we use the calculation ($page * $limit) - $limit): to normalize the value to be used in MYSQL.

  • Next we have a connection to the bank through the PDO.

  • After obtaining the number of existing lines in the news table, we calculate what is the maximum number of pages we can generate. This is done using ceil($result['count'] / $limit. The function ceil has the job of rounding the number up, because we are working with integers.

  • Then we have the SELECT with a LIMIT, where the first argument of LIMIT is the initial offset where we start the query; and the second argument is the limit per page, which in this case is 9, defined in the variable $limit.

  • And finally, we have a for, which generates the links for you to click accordingly and display the results according to the page. I tried to leave the code as organized as possible. So I used the function http_build_query. It generates data in url encoding through a array. When we add up ['page' => $i] + $_GET we are ensuring that the value of page already existing in the $_GET does not overwrite the value we want to have as page inside http_build_query.

See why it’s important to use PDO instead of the duties mysql_*

To understand more about the "array sum", see the explanation in Handbook

  • It was a brief explanation.

  • A little info: you need to know that when you use "limit" Mysql you do "limit" after filtering everything. It means that if you have 100,000 data, Mysql will filter and sort the 100,000 even if you make a "limit" of only 10. In case a lot of information can be slow. In this case it is better to try to make a SELECT using a value. For example, in the case of "filter by price", create a query with "price less than and greater than" and evolve the page price after page.

  • Are you sure? A query to a table with 10,000 data seems faster when using the LIMIT!

  • No, but slow. What makes you think it’s but fast and why you look at the result on your screen. On the Web, it has speed of SQL, PHP but also of data transmission: when you do a LIMIT from the point of view of SQL and but slow, but as you receive only a small amount of data, the result "visual" and but fast. So the problem starts to happen only when you have a lot of information with complicated "query".

  • Thanks gentlemen, I’ll look here! Abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.