简体   繁体   English

在 PHP 中限制每页的帖子

[英]Limit posts per page in PHP

I need to limit how many posts appear on the homepage of my site.我需要限制我网站主页上显示的帖子数量。

It currently appears like this: http://prntscr.com/j5nhng目前看起来是这样的: http://prntscr.com/j5nhng

I want to be able to limit 3 posts per page.我希望能够限制每页 3 个帖子。 I do not know whether to be <href =.不知是否可以<href =. There may be some mistake, but I appreciate any help you can give me.可能有一些错误,但我很感激你能给我的任何帮助。 From already thank you从已经谢谢你

My code if you need any variable:我的代码,如果你需要任何变量:

<title>Noticias</title>
<?php
// Connects to the database
include('admin/config.php');
// Selects the ' News ' table where the news data gets
$selecionar_db = "SELECT * FROM news ORDER BY id DESC";
// Faz a Conexão com o banco de dados
$final = mysql_query($selecionar_db)
// Message if you have an error with the database
or die ("<h1>Erro ao Conectar-se ao Banco de dados</h1>");

// Picks up the values from the "news" table
while ($news=mysql_fetch_array($final)) { 
$id = $news["id"];

$titulo = $news["titulo"];

$categoria_id = $news["categoria"];

$autor = $news["autor"];

$views = $news["views"];

$texto = $news["texto"];

$date = $news["date"];

// Altera o Formato da data da noticia
$date2 = strtotime($date);
$data = date('d/m/Y', $date2);
$hora = date('H:i', $date2);

// Pega o número de Comentários que a noticia possui
$comentarios_db = "SELECT * FROM comentarios WHERE noticia_id='$id'";
$comentarios_db = mysql_query($comentarios_db);
$comentarios = mysql_num_rows($comentarios_db);

// Faz a seleção da Categoria
$categoria_db = "SELECT * FROM categorias WHERE id='$categoria_id'";
$categoria_resultado = mysql_query($categoria_db);
$categoria_final = mysql_fetch_assoc($categoria_resultado);
$categoria = $categoria_final['categoria'];


echo "<h1><a href=\"noticia.php?id=$id\">$titulo</a></h1> <p>Postado por <b>$autor</b> em <b>$data</b> ás <b>$hora</b> <p>$texto</p>";


}
?>

You can do this with '[LIMIT][1]' in SQL. Just store the page number in a variable in your PHP, and get the number of results per page in another variable.您可以使用 SQL 中的“[LIMIT][1]”来执行此操作。只需将页码存储在 PHP 中的一个变量中,然后在另一个变量中获取每页的结果数。 Then calculate the first row to display based on your page.然后根据您的页面计算要显示的第一行。 For example: if you want to display 10 results per page, and you are on the second page, then you should start displaying results from row 11.例如:如果你想每页显示 10 个结果,而你在第二页,那么你应该从第 11 行开始显示结果。

Here is an example:这是一个例子:

$page = $_GET['page']; // Let say it stores 2
$resultsPerPage = 10;

$startFrom = ($page-1)*($resultsPerPage); // Will display 10

AND then your SQL should look like this:然后你的 SQL 应该是这样的:

$comentarios_db = "SELECT * FROM commentaries WHERE noticia_id='$id' LIMIT ".$startFrom.", ".$resultsPerPage;

SELECT * FROM news ORDER BY id DESC LIMIT 3 SELECT * 来自新闻 ORDER BY id DESC LIMIT 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM