Ir para conteúdo

POWERED BY:

Arquivado

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

webdesign

Sistema De Comentarios

Recommended Posts

Tenho o seguinte problema coloquei o sistema de comentários no meu site mais concretamente na pagina single.php onde ele posta cada noticia,Só que ele repete todos os comentarios nas noticias todas como faço para que em cada noticia apareça o comentario referente a mesma?vou postar os codigos.

 

 

 

comment.class.php

<?php

class Comment
{
private $data = array();

public function __construct($row)
{
	/*
	/	The constructor
	*/

	$this->data = $row;
}

public function markup()
{
	/*
	/	This method outputs the XHTML markup of the comment
	*/

	// Setting up an alias, so we don't have to write $this->data every time:
	$d = &$this->data;

	$link_open = '';
	$link_close = '';

	if($d['url']){

		// If the person has entered a URL when adding a comment,
		// define opening and closing hyperlink tags

		$link_open = '<a href="'.$d['url'].'">';
		$link_close =  '</a>';
	}

	// Converting the time to a UNIX timestamp:
	$d['dt'] = strtotime($d['dt']);

	// Needed for the default gravatar image:
	$url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';

	return '

		<div class="comment">
			<div class="avatar">
				'.$link_open.'
				<img src="http://www.gravatar.com/avatar/'.md5($d['email']).'?size=50&default='.urlencode($url).'" />
				'.$link_close.'
			</div>

			<div class="name">'.$link_open.$d['name'].$link_close.'</div>
			<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
			<p>'.$d['body'].'</p>
		</div>
	';
}

public static function validate(&$arr)
{
	/*
	/	This method is used to validate the data sent via AJAX.
	/
	/	It return true/false depending on whether the data is valid, and populates
	/	the $arr array passed as a paremter (notice the ampersand above) with
	/	either the valid input data, or the error messages.
	*/

	$errors = array();
	$data	= array();

	// Using the filter_input function introduced in PHP 5.2.0

	if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
	{
		$errors['email'] = 'Digite o seu email.';
	}

	if(!($data['url'] = filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL)))
	{
		// If the URL field was not populated with a valid URL,
		// act as if no URL was entered at all:

		$url = '';
	}

	// Using the filter with a custom callback function:

	if(!($data['body'] = filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
	{
		$errors['body'] = 'Por favor digite um argumento.';
	}

	if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
	{
		$errors['name'] = 'Por favor digite um nome.';
	}

	if(!empty($errors)){

		// If there are errors, copy the $errors array to $arr:

		$arr = $errors;
		return false;
	}

	// If the data is valid, sanitize all the data and copy it to $arr:

	foreach($data as $k=>$v){
		$arr[$k] = mysql_real_escape_string($v);
	}

	// Ensure that the email is lower case:

	$arr['email'] = strtolower(trim($arr['email']));

	return true;

}

private static function validate_text($str)
{
	/*
	/	This method is used internally as a FILTER_CALLBACK
	*/

	if(mb_strlen($str,'utf8')<1)
		return false;

	// Encode all html special characters (<, >, ", & .. etc) and convert
	// the new line characters to <br> tags:

	$str = nl2br(htmlspecialchars($str));

	// Remove the new line characters that are left
	$str = str_replace(array(chr(10),chr(13)),'',$str);

	return $str;
}

}

?>

 

demo.php

 

<?php

class Comment
{
private $data = array();

public function __construct($row)
{
	/*
	/	The constructor
	*/

	$this->data = $row;
}

public function markup()
{
	/*
	/	This method outputs the XHTML markup of the comment
	*/

	// Setting up an alias, so we don't have to write $this->data every time:
	$d = &$this->data;

	$link_open = '';
	$link_close = '';

	if($d['url']){

		// If the person has entered a URL when adding a comment,
		// define opening and closing hyperlink tags

		$link_open = '<a href="'.$d['url'].'">';
		$link_close =  '</a>';
	}

	// Converting the time to a UNIX timestamp:
	$d['dt'] = strtotime($d['dt']);

	// Needed for the default gravatar image:
	$url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';

	return '

		<div class="comment">
			<div class="avatar">
				'.$link_open.'
				<img src="http://www.gravatar.com/avatar/'.md5($d['email']).'?size=50&default='.urlencode($url).'" />
				'.$link_close.'
			</div>

			<div class="name">'.$link_open.$d['name'].$link_close.'</div>
			<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
			<p>'.$d['body'].'</p>
		</div>
	';
}

public static function validate(&$arr)
{
	/*
	/	This method is used to validate the data sent via AJAX.
	/
	/	It return true/false depending on whether the data is valid, and populates
	/	the $arr array passed as a paremter (notice the ampersand above) with
	/	either the valid input data, or the error messages.
	*/

	$errors = array();
	$data	= array();

	// Using the filter_input function introduced in PHP 5.2.0

	if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
	{
		$errors['email'] = 'Digite o seu email.';
	}

	if(!($data['url'] = filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL)))
	{
		// If the URL field was not populated with a valid URL,
		// act as if no URL was entered at all:

		$url = '';
	}

	// Using the filter with a custom callback function:

	if(!($data['body'] = filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
	{
		$errors['body'] = 'Por favor digite um argumento.';
	}

	if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
	{
		$errors['name'] = 'Por favor digite um nome.';
	}

	if(!empty($errors)){

		// If there are errors, copy the $errors array to $arr:

		$arr = $errors;
		return false;
	}

	// If the data is valid, sanitize all the data and copy it to $arr:

	foreach($data as $k=>$v){
		$arr[$k] = mysql_real_escape_string($v);
	}

	// Ensure that the email is lower case:

	$arr['email'] = strtolower(trim($arr['email']));

	return true;

}

private static function validate_text($str)
{
	/*
	/	This method is used internally as a FILTER_CALLBACK
	*/

	if(mb_strlen($str,'utf8')<1)
		return false;

	// Encode all html special characters (<, >, ", & .. etc) and convert
	// the new line characters to <br> tags:

	$str = nl2br(htmlspecialchars($str));

	// Remove the new line characters that are left
	$str = str_replace(array(chr(10),chr(13)),'',$str);

	return $str;
}

}

?>

 

 

 

script.js

$(document).ready(function(){
/* The following code is executed once the DOM is loaded */

/* This flag will prevent multiple comment submits: */
var working = false;

/* Listening for the submit event of the form: */
$('#addCommentForm').submit(function(e){

		e.preventDefault();
	if(working) return false;

	working = true;
	$('#submit').val('Working..');
	$('span.error').remove();

	/* Sending the form fileds to submit.php: */
	$.post('submit.php',$(this).serialize(),function(msg){

		working = false;
		$('#submit').val('Submit');

		if(msg.status){

			/* 
			/	If the insert was successful, add the comment
			/	below the last one on the page with a slideDown effect
			/*/

			$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
			$('#body').val('');
		}
		else {

			/*
			/	If there were errors, loop through the
			/	msg.errors object and display them on the page 
			/*/

			$.each(msg.errors,function(k,v){
				$('label[for='+k+']').append('<span class="error">'+v+'</span>');
			});
		}
	},'json');

});

});

 

 

submit.php

<?php

error_reporting(E_ALL^E_NOTICE);

include "connect.php";
include "comment.class.php";

$arr = array();
$validates = Comment::validate($arr);

if($validates)
{

mysql_query("	INSERT INTO comments(name,url,email,body)
				VALUES (
					'".$arr['name']."',
					'".$arr['url']."',
					'".$arr['email']."',
					'".$arr['body']."'
				)");

$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();


$arr = array_map('stripslashes',$arr);

$insertedComment = new Comment($arr);


echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));

}
else
{
/* Outputtng the error messages */
echo '{"status":0,"errors":'.json_encode($arr).'}';
}

?>

Outra coisa importante que me estava a faltar


CREATE TABLE `comments` (
 `id` int(10) unsigned NOT NULL auto_increment,
 `name` varchar(128) collate utf8_unicode_ci NOT NULL default '',
 `url` varchar(255) collate utf8_unicode_ci NOT NULL default '',
 `email` varchar(255) collate utf8_unicode_ci NOT NULL default '',
 `body` text collate utf8_unicode_ci NOT NULL,
 `dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
 PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Compartilhar este post


Link para o post
Compartilhar em outros sites

Use um campo para na hora do usuario comentar, salvar o id da noticia tambem. Depois faz uma foreign key referenciando a tabela de noticias (id) e no select poe WHERE noticia_id = $noticia_atual, por exemplo.

 

CREATE TABLE `comments` (
 `id` int(10) unsigned NOT NULL auto_increment,
 `name` varchar(128) collate utf8_unicode_ci NOT NULL default '',
 `url` varchar(255) collate utf8_unicode_ci NOT NULL default '',
 `email` varchar(255) collate utf8_unicode_ci NOT NULL default '',
 `body` text collate utf8_unicode_ci NOT NULL,
 'news' int(10)* NOT NULL,
 `dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
 PRIMARY KEY  (`id`)
 FOREIGN KEY(news) REFERENCES nome_tabela_noticias(campo_id)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

 

*lembrando de usar o mesmo tipo de campo, do campo que você for referenciar.

Compartilhar este post


Link para o post
Compartilhar em outros sites

obrigado por tentar ajudar,só que nao estou entendendo muito bem

CREATE TABLE `comments` (
 `id` int(10) unsigned NOT NULL auto_increment,
 `name` varchar(128) collate utf8_unicode_ci NOT NULL default '',
 `url` varchar(255) collate utf8_unicode_ci NOT NULL default '',
 `email` varchar(255) collate utf8_unicode_ci NOT NULL default '',
 `body` text collate utf8_unicode_ci NOT NULL,
 'news' int(10)* NOT NULL,
 `dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
 PRIMARY KEY  (`id`)
 FOREIGN KEY(news) REFERENCES nome_tabela_noticias(campo_id)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

 

 

Este codigo é para inserir na tabela certo!? Se for está a dar um erro e nao insere

#1064 - You have an error in your SQL syntax; check the manual  that corresponds to your MySQL server version for the right syntax to  use near ''news' int(10)* NOT NULL,
`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
P' at line 7 

 

pode explicar melhor com os codigos

!?

 

Use um campo para na hora do usuario comentar, salvar o id da noticia tambem. Depois faz uma foreign key referenciando a tabela de noticias (id) e no select poe WHERE noticia_id = $noticia_atual, por exemplo.

 

CREATE TABLE `comments` (

`id` int(10) unsigned NOT NULL auto_increment,

`name` varchar(128) collate utf8_unicode_ci NOT NULL default '',

`url` varchar(255) collate utf8_unicode_ci NOT NULL default '',

`email` varchar(255) collate utf8_unicode_ci NOT NULL default '',

`body` text collate utf8_unicode_ci NOT NULL,

'news' int(10)* NOT NULL,

`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,

PRIMARY KEY (`id`)

FOREIGN KEY(news) REFERENCES nome_tabela_noticias(campo_id)

) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

 

 

*lembrando de usar o mesmo tipo de campo, do campo que você for referenciar.

Compartilhar este post


Link para o post
Compartilhar em outros sites

'news' int(10)* NOT NULL,

 

syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''news' int(10)*

 

Remova o asterisco depois do int(10)

 

pode explicar melhor com os codigos

 

Não é necessário código para explicar alguma coisa. Seja específico na parte que não entendeu que será simples explicar.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Remova o asterisco depois do int(10)

 

 

 

Não é necessário código para explicar alguma coisa. Seja específico na parte que não entendeu que será simples explicar.

 

dá erro na mesma

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''news' int(10) NOT NULL,

`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,

' at line

Compartilhar este post


Link para o post
Compartilhar em outros sites
CREATE TABLE `comments` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(128) NOT NULL default '',
`url` varchar(255) NOT NULL default '',
`email` varchar(255) NOT NULL default '',
`body` text collate utf8_unicode_ci NOT NULL,
`news` int(10) NOT NULL,
`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FOREIGN KEY(news) REFERENCES nome_tabela_noticias(campo_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Compartilhar este post


Link para o post
Compartilhar em outros sites

Uma sugestão: você conhece o sistema de comentários do facebook? o sistema já lhe dá tudo "de bandeja" (não que isso seja bom xD ). Basta inserir o código na página.

 

Tem um tutorial ótimo do Mestre Seo aqui: http://www.mestreseo.com.br/facebook/novo-sistema-comentarios-facebook

 

 

[]'s

Compartilhar este post


Link para o post
Compartilhar em outros sites

estou a horas a olhar para istu e nada, eu fiz o seguinte coloquei na tabela este codigo

 			     					CREATE TABLE `comments` (
       `id` int(10) unsigned NOT NULL auto_increment,
       `name` varchar(128) NOT NULL default '',
       `url` varchar(255) NOT NULL default '',
       `email` varchar(255) NOT NULL default '',
       `body` text collate utf8_unicode_ci NOT NULL,
       `news` int(10) NOT NULL,
       `dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
       PRIMARY KEY (`id`),
       FOREIGN KEY(news) REFERENCES nome_tabela_noticias(campo_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 			     			

 

depois foi a pagina demo.php e coloquei o were mas nao funcionou nada simplesmente deu erro na linha 19 pode me ajudar a onde tenho que colocar o codigo correcto

<?php

// relatórios de erro:
error_reporting(E_ALL^E_NOTICE);

include "connect.php";
include "comment.class.php";


/*
/	Selecione todos os comentários e preencher o array $ comentários com objetos
*/

$comments = array();
$result = mysql_query("SELECT * FROM comments
                   	WHERE noticia_id = $noticia_atual 
                   	ORDER BY id ASC");

while($row = mysql_fetch_assoc($result))
{
$comments[] = new Comment($row);
}

?>

 

o erro foi este

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/a2372811/public_html/demo.php on line 19

Compartilhar este post


Link para o post
Compartilhar em outros sites

cara nao estou a conseguir e ainda estou aprender istu nao é facil, eu tenho na tabela up_post onde ele posta as noticias

int(11) 			No 		auto_increment 	Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
thumb 	text 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
titulo 	text 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
texto 	text 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
categoria 	text 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
data 	timestamp 		ON UPDATE CURRENT_TIMESTAMP 	Yes 	NULL 	on update CURRENT_TIMESTAMP 	Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
autor 	text 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
valor_real 	text 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
valor_pagseguro 	text 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
visitas 	varchar(11) 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext

só que nem sequer sei como hei de colocar esse codigo na pagina demo.php

Compartilhar este post


Link para o post
Compartilhar em outros sites

Primeiro, você sabe o que é Foreign Key? Se não, de uma olhada: http://www.w3schools.com/sql/sql_foreignkey.asp

 

Você provavelmente tem uma pagina para ler a noticia desejada, certo? por exemplo: seusite.com.br/noticia.php?cod_noticia=1

 

Usando o metodo get, você deve pegar este id.

 

$noticia = $_GET['cod_noticia'];

 

Depois, no sql do comentario, no campo foreign key referente a qual noticia pertence aquele comentario, você insere o codigo da noticia listado acima.

Compartilhar este post


Link para o post
Compartilhar em outros sites

rodrigo está pagina é que posta as noticias pode ser mas especifico para mim para eu poder colocar esses codigos,istu é bem dificil para mim

single.php

<div id="page_content">

<div id="sidebar">
<?php include"sidebars/sidebar.php";?>
</div><!--sidebar-->

  <div id="page">
<?php

$topico = $_GET['topico'];

$noticias = mysql_query("SELECT
					thumb,
					titulo,
					texto,
					categoria,
					`data`,
					autor,
					valor_real,
					valor_pagseguro,
					visitas
					FROM up_posts
					WHERE id = '$topico'")
       	or die(mysql_error());
if(@mysql_num_rows($noticias) <= '0'){
  echo "$info_not";	
}else{

$numero = '0';

	while($res_noticias=mysql_fetch_array($noticias)){

	$thumb = $res_noticias[0];
	$titulo = $res_noticias[1];
	$texto = $res_noticias[2];
	$categoria = $res_noticias[3];
	$data = $res_noticias[4];
	$autor = $res_noticias[5];
	$valor_real = $res_noticias[6];
	$valor_pagseguro = $res_noticias[7];
	$visitas = $res_noticias[8];
	$numero++;

$add_visita = $visitas + 1;
$up_visitas = mysql_query("UPDATE up_posts SET visitas = '$add_visita', data = '$data' WHERE id = '$topico'")
      		or die(mysql_error());


    $pega_autor = mysql_query("SELECT nome FROM up_users WHERE id = '$autor'")
             		or die(mysql_error());
    if(@mysql_num_rows($pega_autor) <= '0') echo 'Erro ao selecionar o usuario';
    else{

     while($res_autor=mysql_fetch_array($pega_autor)){

	     $autor_do_post = $res_autor[0];

?>


<h1><?php echo $titulo;?></h1>
 	<script type="text/javascript"><!--
google_ad_client = "pub-3505393501368142";
/* 468x60, criado 17-07-2010 */
google_ad_slot = "6110824402";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<span class="info">Data: <?php echo date('d/m/Y - H:m', strtotime($data)); ?> | Autor: <?php echo $autor_do_post; ?> | Categoria: <?php echo $categoria; ?> | Visitas: <?php echo $visitas; ?></span>

	<a href="uploads/<?php echo $categoria; ?>/<?php echo $thumb; ?>" rel="shadowbox">
  	<img src="uploads/<?php echo $categoria; ?>/<?php echo $thumb; ?>" class="alinright" alt="<?php echo $titulo; ?>" width="200" title="<?php echo $titulo; ?>"/>
	</a>

	<?php echo $texto;?>
<script type="text/javascript"><!--
google_ad_client = "pub-3505393501368142";
/* 468x60, criado 17-07-2010 */
google_ad_slot = "6110824402";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<div id="social"> 
<ul>
<li>
	<script type="text/javascript">
	tweetmeme_url = 'http://tugafilmes.site11.com/';
	tweetmeme_source = 'conectese';
	</script>
	<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>
</li>   

<li>
    		<a name="fb_share" type="buttom_count" href="http://www.facebook.com/sharer.php"
    		share_url="http://tugafilmes.site11.com/">Curtir</a><script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
</li>

<li>
    		<g:plusone size="small"></g:plusone>
</li>

</ul>

</div>

<?php if($categoria == 'Noticias'){
?>


<?php
}else{
}
?>

<?php
}
}
?>
<?php
}
}
?>
  </div><!--page-->

</div><!--page_content-->

 

niguem consegue me dar uma ajuda nistu já estou a ficar sen cabeça axu que vou desistir!?

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.