喜欢不喜欢的代码在数据库中输入重复值

时间:2015-04-09 06:19:55

标签: php

在我喜欢不喜欢的表中我有3列prod_id,user_id和like_dislike.i我插入0表示不喜欢和1表示like.in下面的代码我插入like_dislike_tbl如果没有特定prod_id的条目和user_id与相同的like_dislike .it,s如果用户改变喜欢不喜欢或反之亦然。但如果用户喜欢他喜欢的任何prod_id,它将输入重复值。这是我的代码。

<?php
session_start();
require('config.php');
$pid=$_REQUEST['prod_id'];
$uid=$_SESSION['uid'];
$act=$_REQUEST['act'];
if ($uid=='') {
header('location:login.php');
}
else
{
$like_sql=mysql_query("SELECT COUNT(*) FROM like_dislike_tbl WHERE 
prod_id='".$pid."' AND user_id='".$uid."' AND like_dislike=1");
$like_count=mysql_result($like_sql, 0);

$dislike_sql=mysql_query("SELECT COUNT(*) FROM like_dislike_tbl WHERE 
prod_id='".$pid."' AND user_id='".$uid."' AND like_dislike=0");
$dislike_count=mysql_result($like_sql, 0);
if($act == 'like'): //if the user click on "like"
    if($like_count == 1){
        header('location:'. $_SERVER['HTTP_REFERER']);
    }
    if(($like_count == 0) && ($dislike_count == 0)){
        mysql_query("INSERT INTO like_dislike_tbl(prod_id,user_id,like_dislike) 
    VALUES('".$pid."','".$uid."',1)");
    }
    if($dislike_count == 1){
        mysql_query('UPDATE like_dislike_tbl SET like_dislike = 1 WHERE 
    prod_id = "'.$pid.'" and user_id ="'.$uid.'"');
    }
    header('location:'. $_SERVER['HTTP_REFERER']);
endif;
if($act == 'dislike'): //if the user click on "dislike"
    if($dislike_count == 1){
        header('location:'. $_SERVER['HTTP_REFERER']);
    }
    if(($like_count == 0) && ($dislike_count == 0)){
        mysql_query("INSERT INTO like_dislike_tbl(prod_id,user_id,like_dislike) 
    VALUES('".$pid."','".$uid."',0)");
    }
    if($like_count == 1){
        mysql_query('UPDATE like_dislike_tbl SET like_dislike = 0 WHERE 
    prod_id = "'.$pid.'" and user_id ="'.$uid.'"');
    }
    header('location:'. $_SERVER['HTTP_REFERER']);
endif;
}
?>

提前告诉我你的建议。如果你不理解我的语言,请不要理解。

我的喜欢_dislike_tbl是

------------------------------------------
|  prod_id  |  user_id  |  like_dislike  |    
------------------------------------------
|    8      |   20      |      0         |
------------------------------------------
|    9      |   20      |      0         |
------------------------------------------
|    8      |   20      |      0         |
------------------------------------------
|    9      |   20      |      0         |
------------------------------------------
|    10     |   20      |      1         |
------------------------------------------
|    10     |   20      |      1         |
------------------------------------------

2 个答案:

答案 0 :(得分:3)

chane your code ....

$dislike_count=mysql_result($like_sql, 0);

这个....

$dislike_count=mysql_result($dislike_sql, 0);

答案 1 :(得分:0)

如果您的表格已经重复,COUNT(*)可能会返回超过1.因此请更改

if (like_count == 1) {

为:

if (like_count >= 1) {

,同样适用于$dislike_count

顺便说一句,你可以通过一个查询得到喜欢和不喜欢的数字:

SELECT SUM(like_dislike = 1) AS like_count, SUM(like_dislike = 0) AS dislike_count
FROM like_dislike_tbl
WHERE prod_id = $pid AND user_id = $uid