terça-feira, 19 de abril de 2016

Notícias em destaque com PHP, PDO e MySQL


Um recurso interessante em qualquer site é destacar as notícias mais recentes; para isso utilizamos a cláusula limit em consultas ao banco de dados. Observe o código a seguir:


<?php
// Aqui a conexão
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    color: #0000FF;
}
.style2 {font-family: Verdana, Arial, Helvetica, sans-serif}
.style3 {font-family: Verdana, Arial, Helvetica, sans-serif; font-weight: bold; }
-->
</style>
</head>

<body>

<table width="697" border="2">
  <tr>
    <th scope="col"><p class="style2 style1">Not&iacute;cias em destaque:</p>
   
<?php

$stmt = $con->prepare("select * from tbnoticias order by idnotic desc limit 3");
$stmt->execute();
while($reg = $stmt->fetch(PDO::FETCH_OBJ))
{
echo $reg->idnotic. " - ";
echo $reg->titulo. " - ";
echo $reg->materia. "<br />";

//echo date('d/m/Y', strtotime($reg->dia)). "<br />";
}

?> <br />
  </tr>
</table>
</p>
<p class="style3">Outras Noticias: </p>

<?php

$stmt2 = $con->prepare("select * from tbnoticias order by idnotic desc limit 3, 10");
$stmt2->execute();
while($reg = $stmt2->fetch(PDO::FETCH_OBJ))
{
echo $reg->idnotic. " - ";
echo $reg->titulo. " - ";
echo $reg->materia. "<br />";

//echo date('d/m/Y', strtotime($reg->dia)). "<br />";
}

?>

</body>
</html>

Veja que na 1ª consulta limitamos as linhas recuperadas a um máximo de três:

$stmt = $con->prepare("select * from tbnoticias order by idnotic desc limit 3");

Serão as noticias em destaque. Já para recuperar as restantes, fazemos outra consulta, descartando aquelas três primeiras e exibindo as restantes (nesse exemplo, são 10):

$stmt2 = $con->prepare("select * from tbnoticias order by idnotic desc limit 3, 10");

Veja um exemplo: