begin process at 2012 05 31 12:08:45
  Trouver un code source :
 
dans
 
Accueil > Forum > 

PHP

 > 

Base de données

 > 

MySQL

 > 

probleme avec un script


Derniers messages déposésPoser une question dans le forum ou lancer une discussion

probleme avec un script

vendredi 4 mars 2011 à 01:36:30 | probleme avec un script

supertony540

salut

je débute en informatique et je suis en train de créer un site perso d'une dizaine de pages.
et je souhaite mettre un système de commentaire sur quelque pages.
Alors j'ai chercher un script de commentaires et j'ai trouver Simple AJAX Commenting System du site tutorialzine.com qui fonctionne très bien sur mon site.
mais quand je l'installe sur une 2émé page les commentaires de la 1ére page si trouve aussi.
ma question est comment faire pour avoir les commentaires propre à chaque page.
j'ai lu sur le site que c'était possible mais je ne sais pas comment faire.

voici les pages du script

demo.php

Code PHP :
<?php

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

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


/*
/	Select all the comments and populate the $comments array with objects
*/

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

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

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple AJAX Commenting System | Tutorialzine demo</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>



<h1>Simple AJAX Commenting System</h1>
<h2><a href="http://tutorialzine.com/2010/06/simple-ajax-commenting-system/">Go Back to Tutorialzine &raquo;</a></h2>

<div id="main">

<?php

/*
/	Output the comments one by one:
*/

foreach($comments as $c){
	echo $c->markup();
}

?>

<div id="addCommentContainer">
	<p>Add a Comment</p>
	<form id="addCommentForm" method="post" action="">
    	<div>
        	<label for="name">Your Name</label>
        	<input type="text" name="name" id="name" />
            
            <label for="email">Your Email</label>
            <input type="text" name="email" id="email" />
            
            <label for="url">Website (not required)</label>
            <input type="text" name="url" id="url" />
            
            <label for="body">Comment Body</label>
            <textarea name="body" id="body" cols="20" rows="5"></textarea>
            
            <input type="submit" id="submit" value="Submit" />
        </div>
    </form>
</div>

</div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>

</body>
</html>


comment.class.php

Code 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&amp;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'] = 'Please enter a valid 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'] = 'Please enter a comment body.';
		}
		
		if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
		{
			$errors['name'] = 'Please enter a name.';
		}
		
		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;
	}

}

?>


submit.php

Code PHP :
<?php

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

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

/*
/	This array is going to be populated with either
/	the data that was sent to the script, or the
/	error messages.
/*/

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

if($validates)
{
	/* Everything is OK, insert to database: */
	
	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();
	
	/*
	/	The data in $arr is escaped for the mysql query,
	/	but we need the unescaped variables, so we apply,
	/	stripslashes to all the elements in the array:
	/*/
	
	$arr = array_map('stripslashes',$arr);
	
	$insertedComment = new Comment($arr);

	/* Outputting the markup of the just-inserted comment: */

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

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

?>


script

Code Javascript :
$(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');

	});
	
});


table

Code :
--
-- Table structure for table `comments`
--

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;


merci de m'aider a modifier le script
vendredi 4 mars 2011 à 10:27:31 | Re : probleme avec un script

ludwig59

Bonjour,

Voici quelques étapes qui vous permettront d'avoir des commentaires différents par page.

1) Ajout un champ idpage de type "int" dans la table comment. Ce champ permettra de savoir à quelle page appartient le commentaire.
Je pars du principe que chaque aura un numéro unique que vous définirez.

2) Ajouter dans le formulaire d'ajout de commentaire :
Code HTML :
<input type="hidden" name="idpage" value="VALUE_DE_LA_PAGE" />

VALUE_DE_LA_PAGE sera le numéro unique de la page.

3) Dans la fonction validate de la class comment, Ajouter :
Code PHP :
if(!($data['idpage'] = filter_input(INPUT_POST,'idpage,FILTER_VALIDATE_INT)))
{
	$data['idpage'] = 0;
}


4) Dans submit.php modifier la requête pour enregistrer l'identifiant de la page.
Code PHP :
mysql_query("	INSERT INTO comments(name,url,email,body,idpage)

					VALUES (
						'".$arr['name']."',
						'".$arr['url']."',
						'".$arr['email']."',
						'".$arr['body']."',
                                                '".$arr['idpage']."'
					)");



5) Et enfin, modifier la requête de selection dans chaque page pour ne prendre que les commentaires de la page en cours :
Code PHP :
$result = mysql_query("SELECT * FROM comments WHERE idpage = 'VALUE_DE_LA_PAGE' ORDER BY id ASC");


Voilà, j'ai détaillé les étapes pour être compréhensible.
vendredi 4 mars 2011 à 15:31:48 | Re : probleme avec un script

supertony540

salut ludwig59

merci d'avoir pris le temps de me répondre, mais je ne comprend pas comment définir un numéro unique.
pourriez vous mettre un exemple facile a comprendre.
ou si ce n'est pas trop demander que vous apportiez les modification au script.

Merci encore
vendredi 4 mars 2011 à 15:34:51 | Re : probleme avec un script

ludwig59

Vous dites que vous avez plusieurs pages. Vous avez un fichier PHP par page ?
Si c'est le cas, vous définissez en début de chaque fichier une variable $numeroPage qui permettra d'identifier chaque page.
vendredi 22 avril 2011 à 00:26:48 | Re : probleme avec un script

apocal86

Merci j'avais le même problème et j'ai même corrigé une petite erreur que tu a placé.

petite correction sur le code pour la class (erreur sur 'idpage')

if(!($data['idpage'] = filter_input(INPUT_POST,'idpage',FILTER_VALIDATE_INT)))
{
$data['idpage'] = 0;
}



Cette discussion est classée dans : code, data, url, errors, if


Répondre à ce message

Sujets en rapport avec ce message

Url en php [ par breezer666cs ] J'ai 1 bouton et un hyperlink dans mon code:            BOBj'essaie csv vers base de donnée [ par fraisa1985 ] Salut a tous, je veux faire une actualisation de ma base de donnée à partir d'une fichier csv. Ma probléme que le fichier csv contient des données pl foreach [ par thedeejay ] Bonjour à tous!je suis en train de réalsier un aspirateur de foru...enfin bref, un code  (légal, d LOAD DATA INFILE [ par Ninie972 ] bonjour, J'aimerais savoir si c'est possible de faire un load data infile (importation de fichier) en spécifiant à la fois le nom des colonnes du fich Image de fond sur carte visite Outlook (Classe VCARD) [ par flopad ] Bonjour tout le monde,j'utilise la classe vcard c-dessous afin de permettre de télécharger les cartes de visites du personnel sur mon annuaire intrane Pagination [ par zendooo ] Bonjour, je viens de ressortir un script que j'avais acheté il y a longtemps, je souhaite modifier la pagination qui affiche toutes les pages. Je voud exec() erreur 1 non justifié [ par Bikarfioul ] Salut ! J'ai un legé différent avec mon serveur PHP. En effet si je tape une commande de ce style sous une console [CODE] rsh toto -l root -n /sc code pour masquer une url mais..... [ par Dav_c ] Voici le code en php Le but étant de masquer l'url dans un lecteur flv mais je me suis rendu compte Petit souci référencement / htaccess / url rewrite etc [ par karistote ] Bonjour :)Voila mon souci : J'ai plusieurs petits sites qui reprennent la même base, mais avec des données différentes. Je me suis amusé à créer des d


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

Photothèque

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,343 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales