Systeme like dislike [Fermé]

Signaler
-
 placi2 -
Bonjour a tous.
je suis entrain de faire un systeme de vote like dislike
mais je trouver que l'utilisateur peut évaluer plusieurs fois pour le même article.
alors j'aimerai empêcher les utilisateurs de vote plusieurs fois
je vais controle si le vote et le login existe deja mais je ne sais pas comment y faire

5 réponses

Messages postés
31454
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
22 février 2021
3 276
Bonjour,

Je déplace ta question dans le forum PHP ... merci d'y penser à l'avenir..

Concernant ta question... je t'ai indiqué dans ton pécédent sujet que tu devais vérifier, via une requête SELECT / WHERE si un vote était déjà présent pour le user ou non...
Qu'en as tu fait ? Tu as essayé de coder quelque-chose au moins ?

En plus... vous que nous ne savons rien de la structure de tes tables... il nous sera extrêmement compliqué de t’apporter une réponse.

Merci donc de nous fournir :
- Le code php qui te sert à te connecter à ta BDD (en occultant les données sensibles)
- La structure de tes tables (via un DUMP de préférence)
- Le code PHP/Html qui te sert actuellement pour réaliser tes votes




2
Merci

Quelques mots de remerciements seront grandement appréciés. Ajouter un commentaire

CCM 65492 internautes nous ont dit merci ce mois-ci

voici ma table

CREATE TABLE `tutorials` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`details` text COLLATE utf8_unicode_ci NOT NULL,
`image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`like_num` bigint(10) NOT NULL,
`dislike_num` bigint(10) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Messages postés
31454
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
22 février 2021
3 276
..... il manque encore des infos....
A quoi correspondent les différents champs ?
Quel est le code PHP qui te sert à voter ?
rating.php

<?php
include_once("tutorial.php");
$tutorial = new Tutorial();
if($_POST['id']){
//previous tutorial data
$prev_record = $tutorial->get_rows($_POST['id']);
//previous total likes
$prev_like = $prev_record['like_num'];
//previous total dislikes
$prev_dislike = $prev_record['dislike_num'];

//calculates the numbers of like or dislike
if($_POST['type'] == 1){
$like = ($prev_like + 1);
$dislike = $prev_dislike;
$return_count = $like;
}else{
$like = $prev_like;
$dislike = ($prev_dislike + 1);
$return_count = $dislike;
}

//store update data
$data = array('like_num'=>$like,'dislike_num'=>$dislike,'modified'=>date("Y-m-d H:i:s"));
//update condition
$condition = array('id'=>$_POST['id']);
//update tutorial like dislike
$update = $tutorial->update($data,$condition);

//return like or dislike number if update is successful, otherwise return error
echo $update?$return_count:'err';
}
?>
tutorial.php

<?php
class Tutorial{

function __construct(){
//db details
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'new_vote';

//connect db
$con = mysql_connect($db_host, $db_user, $db_pass);

//select db
mysql_select_db($db_name, $con);
}

function get_rows($id = ''){
if($id != ''){
//fetch single row
$query = mysql_query("SELECT * FROM tutorials WHERE id = $id");
$data = mysql_fetch_assoc($query);
}else{
//fetch all rows
$query = mysql_query("SELECT * FROM tutorials");
while($row = mysql_fetch_assoc($query)){
$data[] = $row;
}
}
return $data;
}

function insert($data = array()){
$data_array_num = count($data);
$columns = "";
$values = "";
$i=0;
foreach($data as $key=>$val){
$i++;
$sep = ($i == $data_array_num)?"":", ";
$columns .= $key.$sep;
$values .= $val.$sep;
}
$insert = mysql_query("INSERT INTO tutorials ($columns) VALUES ($values)");
return $insert?TRUE:FALSE;
}

function update($data = array(), $conditions = array()){
$data_array_num = count($data);
$cols_vals = "";
$condition_str = "";
$i=0;
foreach($data as $key=>$val){
$i++;
$sep = ($i == $data_array_num)?'':', ';
$cols_vals .= $key."='".$val."'".$sep;
}
foreach($conditions as $key=>$val){
$i++;
$sep = ($i == $data_array_num)?"":" AND ";
$condition_str .= $key."='".$val."'";
}

$update = mysql_query("UPDATE tutorials SET $cols_vals WHERE $condition_str");
return $update?TRUE:FALSE;
}
}
?>
index.php

<?php
include_once("tutorial.php");
$tutorial = new Tutorial();
$trows = $tutorial->get_rows();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Like and Dislike using jQuery, Ajax and PHP</title>
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css"/>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<style type="text/css">
.row{ margin:20px 20px 20px 20px;}
.ratings{ font-size:25px !important;}
.thumbnail img {
width: 100%;
}

.ratings {
padding-right: 10px;
padding-left: 10px;
color: #d17581;
}

.thumbnail {
padding: 0;
}

.thumbnail .caption-full {
padding: 9px;
color: #333;
}
.glyphicon-thumbs-up:hover{ color:#008000; cursor:pointer;}
.glyphicon-thumbs-down:hover{ color: #E10000; cursor:pointer;}
.counter{ color:#333333;}
.thumbnail img{height:200px;}
</style>

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
/**
  • Function Name: cwRating()
  • Function Author: CodexWorld
  • Description: cwRating() function is used for implement the rating system. cwRating() function insert like or dislike data into the database and display the rating count at the target div.
  • id = Unique ID, like or dislike is based on this ID.
  • type = Use 1 for like and 0 for dislike.
  • target = Target div ID where the total number of likes or dislikes will display.
    • /

function cwRating(id,type,target){
$.ajax({
type:'POST',
url:'rating.php',
data:'id='+id+'&type='+type,
success:function(msg){
if(msg == 'err'){
alert('Some problem occured, please try again.');
}else{
$('#'+target).html(msg);
}
}
});
}
</script>
</head>

<body>
<div class="row wel">
<?php foreach($trows as $trow){ ?>
<div class="col-sm-4 col-lg-4 col-md-4 well">
<div class="thumbnail">
<img src="<?php echo 'images/'.$trow['image']; ?>" alt="" / class="well">
<div class="caption">
<h4><a href="javascript:void(0);" rel="nofollow noopener noreferrer" target="_blank"><?php echo $trow['title']; ?></a></h4>
<p><?php echo $trow['details']; ?></p>
</div>
<div class="ratings">
<p class="pull-right"></p>
<p>
<!-- Like Icon HTML -->
<span class="glyphicon glyphicon-thumbs-up" onClick="cwRating(<?php echo $trow['id']; ?>,1,'like_count<?php echo $trow['id']; ?>')"></span> 
<!-- Like Counter -->
<span class="counter" id="like_count<?php echo $trow['id']; ?>"><?php echo $trow['like_num']; ?></span>   

<!-- Dislike Icon HTML -->
<span class="glyphicon glyphicon-thumbs-down" onClick="cwRating(<?php echo $trow['id']; ?>,0,'dislike_count<?php echo $trow['id']; ?>')"></span> 
<!-- Dislike Counter -->
<span class="counter" id="dislike_count<?php echo $trow['id']; ?>"><?php echo $trow['dislike_num']; ?></span>

<!-- LikeBtn.com BEGIN -->
<span class="likebtn-wrapper" data-identifier="item_1"></span>
<script>(function(d,e,s){if(d.getElementById("likebtn_wjs"))return;
a=d.createElement(e);
m=d.getElementsByTagName(e)[5];
a.async=10;a.id="likebtn_wjs";
a.src=s;m.parentNode.insertBefore(a, m)})(document,"script","//w.likebtn.com/js/w/widget.js");
</script>
<!-- LikeBtn.com END -->
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</body>
</html>
Messages postés
31454
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
22 février 2021
3 276 > placi2
... peut être ... mais en attendant ... tu n'as toujours pas posté ton code en utilisant LES BALISES DE CODE.
Tant que ça ne sera pas fait .. je ne regarderai pas !


Voir ici : Comment utiliser les BALISES DE CODE


.
merci Jordane.ce juste que je ne savais pas la ou passe pour utiliser le balise code

tutorials.sql:


-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Dec 16, 2014 at 11:16 AM
-- Server version: 5.5.24-log
-- PHP Version: 5.3.13

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `tutorials`
--

CREATE TABLE IF NOT EXISTS `tutorials` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `details` text COLLATE utf8_unicode_ci NOT NULL,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `like_num` bigint(10) NOT NULL,
  `dislike_num` bigint(10) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

--
-- Dumping data for table `tutorials`
--

INSERT INTO `tutorials` (`id`, `title`, `details`, `image`, `like_num`, `dislike_num`, `created`, `modified`, `status`) VALUES
(1, 'Upload image and create thumbnail using PHP', 'This short tutorial will explain how you upload images and create thumbnail of the images using PHP.', 'upload-image-create-thumbnail-using-php.png', 5, 1, '2014-12-15 00:00:00', '2014-12-15 09:08:56', 1),
(2, 'Create Custom Shortcode in WordPress', 'WordPress introduced Shortcode API in version 2.5. Shortcode is a set of functions for creating macro codes.', 'wordpress-shortcode.png', 6, 3, '2014-12-15 00:00:00', '2014-12-16 05:23:20', 1);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
tutorial.php


<?php
class Tutorial{
	
	function __construct(){
		//db details
		$db_host = 'localhost';
		$db_user = 'root';
		$db_pass = '';
		$db_name = 'new_vote';
		
		//connect db
		$con = mysql_connect($db_host, $db_user, $db_pass);
		
		//select db
		mysql_select_db($db_name, $con);
	}
	
	function get_rows($id = ''){
		if($id != ''){
			//fetch single row
			$query = mysql_query("SELECT * FROM tutorials WHERE id = $id");
			$data = mysql_fetch_assoc($query);
		}else{
			//fetch all rows
			$query = mysql_query("SELECT * FROM tutorials");
			while($row = mysql_fetch_assoc($query)){
				$data[] = $row;
			}
		}
		return $data;
	}
	
	function insert($data = array()){
		$data_array_num = count($data);
		$columns = "";
		$values = "";
		$i=0;
		foreach($data as $key=>$val){ 
			$i++;
			$sep = ($i == $data_array_num)?"":", ";
			$columns .= $key.$sep;
			$values .= $val.$sep;
		}
		$insert = mysql_query("INSERT INTO tutorials ($columns) VALUES ($values)");
		return $insert?TRUE:FALSE;
	}
	
	function update($data = array(), $conditions = array()){
		$data_array_num = count($data);
		$cols_vals = "";
		$condition_str = "";
		$i=0;
		foreach($data as $key=>$val){
			$i++;
			$sep = ($i == $data_array_num)?'':', ';
			$cols_vals .= $key."='".$val."'".$sep;
		}
		foreach($conditions as $key=>$val){
			$i++;
			$sep = ($i == $data_array_num)?"":" AND ";
			$condition_str .= $key."='".$val."'";
		}

		$update = mysql_query("UPDATE tutorials SET $cols_vals WHERE $condition_str");
		return $update?TRUE:FALSE;
	}
}
?>

rating.php


<?php
include_once("tutorial.php");
$tutorial = new Tutorial();
if($_POST['id']){
	//previous tutorial data
	$prev_record = $tutorial->get_rows($_POST['id']);
	//previous total likes
	$prev_like = $prev_record['like_num'];
	//previous total dislikes
	$prev_dislike = $prev_record['dislike_num'];
	
	//calculates the numbers of like or dislike
	if($_POST['type'] == 1){
		$like = ($prev_like + 1);
		$dislike = $prev_dislike;
		$return_count = $like;
	}else{
		$like = $prev_like;
		$dislike = ($prev_dislike + 1);
		$return_count = $dislike;
	}
	
	//store update data
	$data = array('like_num'=>$like,'dislike_num'=>$dislike,'modified'=>date("Y-m-d H:i:s"));
	//update condition
	$condition = array('id'=>$_POST['id']);
	//update tutorial like dislike
	$update = $tutorial->update($data,$condition);
	
	//return like or dislike number if update is successful, otherwise return error
	echo $update?$return_count:'err';
}
?>

index.php


<?php
include_once("tutorial.php");
$tutorial = new Tutorial();
$trows = $tutorial->get_rows();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Like and Dislike using jQuery, Ajax and PHP</title>
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css"/>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<style type="text/css">
.row{ margin:20px 20px 20px 20px;}
.ratings{ font-size:25px !important;}
.thumbnail img {
    width: 100%;
}

.ratings {
    padding-right: 10px;
    padding-left: 10px;
    color: #d17581;
}

.thumbnail {
    padding: 0;
}

.thumbnail .caption-full {
    padding: 9px;
    color: #333;
}
.glyphicon-thumbs-up:hover{ color:#008000; cursor:pointer;}
.glyphicon-thumbs-down:hover{ color: #E10000; cursor:pointer;}
.counter{ color:#333333;}
.thumbnail img{height:200px;}
</style>

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
/**
* Function Name: cwRating()
* Function Author: CodexWorld
* Description: cwRating() function is used for implement the rating system. cwRating() function insert like or dislike data into the database and display the rating count at the target div.
* id = Unique ID, like or dislike is based on this ID.
* type = Use 1 for like and 0 for dislike.
* target = Target div ID where the total number of likes or dislikes will display.
**/
function cwRating(id,type,target){
	$.ajax({
		type:'POST',
		url:'rating.php',
		data:'id='+id+'&type='+type,
		success:function(msg){
			if(msg == 'err'){
				alert('Some problem occured, please try again.');
			}else{
				$('#'+target).html(msg);
			}
		}
	});
}
</script>
</head>

<body>
<div class="row wel">
	<?php foreach($trows as $trow){ ?>
    <div class="col-sm-4 col-lg-4 col-md-4 well">
        <div class="thumbnail">
            <img src="<?php echo 'images/'.$trow['image']; ?>" alt="" / class="well">
            <div class="caption">
                <h4><a href="javascript:void(0);" rel="nofollow noopener noreferrer" target="_blank"><?php echo $trow['title']; ?></a></h4>
                <p><?php echo $trow['details']; ?></p>
            </div>
            <div class="ratings">
                <p class="pull-right"></p>
                <p>
                    <!-- Like Icon HTML -->
                    <span class="glyphicon glyphicon-thumbs-up" onClick="cwRating(<?php echo $trow['id']; ?>,1,'like_count<?php echo $trow['id']; ?>')"></span> 
                    <!-- Like Counter -->
                    <span class="counter" id="like_count<?php echo $trow['id']; ?>"><?php echo $trow['like_num']; ?></span>   
                    
                    <!-- Dislike Icon HTML -->
                    <span class="glyphicon glyphicon-thumbs-down" onClick="cwRating(<?php echo $trow['id']; ?>,0,'dislike_count<?php echo $trow['id']; ?>')"></span> 
                    <!-- Dislike Counter -->
                    <span class="counter" id="dislike_count<?php echo $trow['id']; ?>"><?php echo $trow['dislike_num']; ?></span>

                    <!-- LikeBtn.com BEGIN -->
                    <span class="likebtn-wrapper" data-identifier="item_1"></span>
                    <script>(function(d,e,s){if(d.getElementById("likebtn_wjs"))return;
                        a=d.createElement(e);
                        m=d.getElementsByTagName(e)[5];
                        a.async=10;a.id="likebtn_wjs";
                        a.src=s;m.parentNode.insertBefore(a, m)})(document,"script","//w.likebtn.com/js/w/widget.js");
                    </script>
                    <!-- LikeBtn.com END -->
                </p>
            </div>
        </div>
    </div>
    <?php } ?>
</div>
</body>
</html>