Dynamic site with multiple result pages

0

I'm doing a project for a dynamic website in college and wanted to know how to mount those result pages with first, second pages and so on without creating new .php files.

For example:

I have a news site, when the user clicks on a topic, the site will be redirected to a page with news related to the subject and a maximum of 10 news items will be shown on each page.

As I do for when user clicks the button on the 2nd page, it will be redirected to a page with the news from 11-20, and so on, on the 3rd page the news from 21-30 ...; without creating a php file for subsequent pages as it can become very large.

    
asked by anonymous 25.09.2014 / 15:57

1 answer

7

You search for pagination in PHP, before that you need to understand what pagination is. Result Paging is quite simple.

We do a search on a particular database table, and with the result of the search, we divide the number of records by a specific number to display per page.

For example a total of 200 records, and we want to display 20 per page, we will soon have 200/20 = 10 pages. Simple, right? Well let's go there for the code then.

  

First connect to MySQL:

<?php
 $conn = mysql_connect("host","usuario","senha");
 $db = mysql_select_db("bancodedados");
?>
  

Now let's create the SQL clause that should be executed:

<?php
 $busca = "SELECT * FROM tabelax";
?>
  

Let's get to work ... Specify the total number of records to display per page:

<?php
  $total_reg = "10"; // número de registros por página
?>
  

If the page is not specified the variable "page" will take a value of 1, this will avoid displaying the start page 0:

<?php
 $pagina=$_GET['pagina'];
 if (!$pagina) {
  $pc = "1";
 } else {
  $pc = $pagina;
 }
?>
  

Let's determine the initial value of the limited searches:

<?php
  $inicio = $pc - 1;
  $inicio = $inicio * $total_reg;
?>
  

Let's select the data and display the pagination:

<?php
  $limite = mysql_query("$busca LIMIT $inicio,$total_reg");
  $todos = mysql_query("$busca");

  $tr = mysql_num_rows($todos); // verifica o número total de registros
  $tp = $tr / $total_reg; // verifica o número total de páginas

  // vamos criar a visualização
  while ($dados = mysql_fetch_array($limite)) {
    $nome = $dados["nome"];
    echo "Nome: $nome<br>";
  }

  // agora vamos criar os botões "Anterior e próximo"
  $anterior = $pc -1;
  $proximo = $pc +1;
  if ($pc>1) {
    echo " <a href='?pagina=$anterior'><- Anterior</a> ";
  }
  echo "|";
  if ($pc<$tp) {
    echo " <a href='?pagina=$proximo'>Próxima -></a>";
  }
 ?>
  

Ready, our PHP pagination is in place!

     

Read more in: Paging in PHP link

     

Source: link

    
25.09.2014 / 16:33