Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Von_Reibnitz

[Resolvido] Exibir as 5 noticias mais lidas no portal

Recommended Posts

Olá, estou com alguns probleminhas aqui, pois bem possuo uma tabela de noticias no bd assim:

--
-- Estrutura da tabela `noticias`
--

CREATE TABLE IF NOT EXISTS `noticias` (
  `id` int(5) NOT NULL auto_increment,
  `id_user` varchar(5) NOT NULL default '4',
  `id_cat` char(3) NOT NULL default '',
  `data` datetime NOT NULL default '0000-00-00 00:00:00',
  `data2` datetime NOT NULL default '0000-00-00 00:00:00',
  `titulo` text NOT NULL,
  `subtitulo` text,
  `texto` text NOT NULL,
  `foto` varchar(255) default NULL,
  `fotos_extras` enum('S','N') NOT NULL default 'N',
  `creditos_fotos` varchar(255) NOT NULL default '',
  `alinhamento_foto` enum('L','R') NOT NULL default 'L',
  `largura_foto` char(3) NOT NULL default '250',
  `altura_foto` char(3) NOT NULL default '',
  `status` enum('S','N') NOT NULL default 'S',
  `cont` bigint(20) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=643 ;

--
-- Extraindo dados da tabela `noticias`
--

pretendo exibir as 5 notícias mais lidas, estou executando desta forma:

 

<?
$sql = mysql_query("SELECT * FROM noticias where cont order by cont desc");
$dados=mysql_fetch_array($sql);
?>
<table width='100%' border='0' cellpadding='4' cellspacing='0'>

  <TR valign="top"> 
    <TD valign="middle" style="border-bottom:#336633 1px dashed; font-size:10px; font-family:Verdana, Arial, Helvetica, sans-serif;" >    <?
$contatamanho = strlen($dados[titulo]);
if(empty($quantidade)){
$quantidade = 110;
}
//$quantidade = 110;
if($contatamanho > $quantidade){
$titulo = substr_replace($dados[titulo], "...", $quantidade, $contatamanho - $quantidade);
} else {
$titulo = "$dados[titulo]";
}

$data = explode("-", $dados[data]);
$data = "$data[2]/$data[1]/$data[0]";

echo "<li style='color:#336633'><a class='ulti' href='?pg=noticia&id=$dados[id]'><b><font size=1 color=#336633>$dados_[nome]</font></b><br>$titulo</a></li>";
?></TD>
  </TR>
  <TR valign="top">
    <TD valign="middle" style="border-bottom:#336633 1px dashed; font-size:10px; font-family:Verdana, Arial, Helvetica, sans-serif;" ><?
$contatamanho = strlen($dados1[titulo]);
if(empty($quantidade)){
$quantidade = 110;
}
//$quantidade = 110;
if($contatamanho > $quantidade){
$titulo1 = substr_replace($dados1[titulo], "...", $quantidade, $contatamanho - $quantidade);
} else {
$titulo1 = "$dados1[titulo]";
}

$data1 = explode("-", $dados1[data]);
$data1 = "$data[2]/$data[1]/$data[0]";

echo "<li style='color:#336633'><a class='ulti' href='?pg=notícia&id=$dados1[id]'><b><font size=1 color=#336633>$dados_2[nome]</font></b><br>$titulo1</a></li>";
?></TD>
  </TR>
  <TR valign="top">
    <TD valign="middle" style="border-bottom:#336633 1px dashed; font-size:10px; font-family:Verdana, Arial, Helvetica, sans-serif;" ><?
$contatamanho = strlen($dados2[titulo]);
if(empty($quantidade)){
$quantidade = 110;
}
//$quantidade = 110;
if($contatamanho > $quantidade){
$titulo2 = substr_replace($dados[titulo], "...", $quantidade, $contatamanho - $quantidade);
} else {
$titulo2 = "$dados2[titulo]";
}

$data2 = explode("-", $dados2[data]);
$data2 = "$data[2]/$data[1]/$data[0]";

echo "<li style='color:#336633'><a class='ulti' href='?pg=notícia&id=$dados2[id]'><b><font size=1 color=#336633>$dados_3[nome]</font></b><br>$titulo2</a></li>";
?></TD>
  </TR>
  
</table>

quiz aproveitar um código já existente e altera-lo mas esta exibindo apenas uma notícia.

 

onde estou errando?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Amigo Von_Reibnitz a primeira coisa a fazer é corrigir a query que possui um WHERE redundante e sem limites.

 

Troque:

 

$sql = mysql_query("SELECT * FROM noticias where cont order by cont desc");
Por:

 

$sql = mysql_query('SELECT * FROM noticias ORDER BY cont DESC LIMIT 5');
Assim você seleciona apenas as 5 noticias desejadas.

 

O Código html onde você exibe os dados esta dentro de um loop?

Se não estiver, de fato ele só vai exibir um registro.

 

Abaixo vai um exemplo teste para que você entenda o que deve fazer:

 

$sql = 'SELECT * FROM noticias ORDER BY cont DESC LIMIT 5';
$executa = mysql_query($sql);
while($row = mysql_fetch_array($executa)) {
    echo "Titulo: ".$row['titulo']."\n";
    echo "Descrição: ".$row['texto']."\n";
}
Abraços.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Uma maneira de se exibir as mais lidas seria criar um campo ex "contador", e a cada exibição da mesma um update alterando o valor.

Compartilhar este post


Link para o post
Compartilhar em outros sites

E ele criou amigo RomanMG. O campo cont da tabela postada por ele no tópico faz justamente esta função.

 

Abraços.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá, olha só fiz assim:

<?
$sql = 'SELECT * FROM noticias ORDER BY cont DESC LIMIT 5';
$executa = mysql_query($sql);
while($row = mysql_fetch_array($executa)) {    
echo "<li style='color:#336633'><a href='?pg=noticia&id=".$row['id']."'><b><font size=1 color=#336633> ".$row['titulo']."</li>";
}
?>

Funcionou beleza.

 

aproveitando o auxílio, gostaria de saber como exibir dados de duas tabelas simultaneamente.

Por exemplo:

-- 
-- Estrutura da tabela `noticias`
-- 

CREATE TABLE `noticias` (
  `id` int(5) NOT NULL auto_increment,
  `id_user` varchar(5) NOT NULL default '4',
  `id_cat` char(3) NOT NULL default '',
  `data` datetime NOT NULL default '0000-00-00 00:00:00',
  `data2` datetime NOT NULL default '0000-00-00 00:00:00',
  `titulo` text NOT NULL,
  `subtitulo` text,
  `texto` text NOT NULL,
  `foto` varchar(255) default NULL,
  `fotos_extras` enum('S','N') NOT NULL default 'N',
  `creditos_fotos` varchar(255) NOT NULL default '',
  `alinhamento_foto` enum('L','R') NOT NULL default 'L',
  `largura_foto` char(3) NOT NULL default '250',
  `altura_foto` char(3) NOT NULL default '',
  `status` enum('S','N') NOT NULL default 'S',
  `cont` bigint(20) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=595 ;

e

-- 
-- Estrutura da tabela `noticias_cat`
-- 

CREATE TABLE `noticias_cat` (
  `id` int(3) NOT NULL auto_increment,
  `nome` varchar(255) NOT NULL default '',
  `status` enum('S','N') NOT NULL default 'S',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=74 ;

pois gostaria de exibir o nome da categoria a que se relaciona a mensagem também.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Pesquise no Google sobre INNER JOIN MySQL.

 

Você vai achar a resposta para sua dúvida.

 

Abraços.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.