Ir para conteúdo

POWERED BY:

Arquivado

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

fsales_123

Sistema

Recommended Posts

CODIGO

<?php
	####### db config ##########
	$db_username = 'root';
	$db_password = '';
	$db_name = 'teste';
	$db_host = 'localhost';
	####### db config end ##########

if($_POST)
{
		
	### connect to mySql
	$sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');

	//get type of vote from client
	$user_vote_type = trim($_POST["vote"]);
	
	//get unique content ID and sanitize it (cos we never know).
	$unique_content_id = filter_var(trim($_POST["unique_id"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
	
	//Convert content ID to MD5 hash (optional)
	$unique_content_id = hash('md5', $unique_content_id);
	
	//check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    } 
	

	switch ($user_vote_type)
	{			
		
		##### User liked the content #########
		case 'up': 
			
			//check if user has already voted, determined by unique content cookie
			if (isset($_COOKIE["voted_".$unique_content_id]))
			{
				header('HTTP/1.1 500 Already Voted'); //cookie found, user has already voted
				exit(); //exit script
			}
			
			//get vote_up value from db using unique_content_id
			$result = mysqli_query($sql_con,"SELECT vote_up FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
			$get_total_rows = mysqli_fetch_assoc($result);
			
			if($get_total_rows)
			{
				//found record, update vote_up the value
				mysqli_query($sql_con,"UPDATE voting_count SET vote_up=vote_up+1 WHERE unique_content_id='$unique_content_id'");
			}else{
				//no record found, insert new record in db
				mysqli_query($sql_con,"INSERT INTO voting_count (unique_content_id, vote_up) value('$unique_content_id',1)");
			}
			
			setcookie("voted_".$unique_content_id, 1, time()+7200); // set cookie that expires in 2 hour "time()+7200".
			echo ($get_total_rows["vote_up"]+1); //display total liked votes
			break;	
		
		##### User disliked the content #########
		case 'down': 
			
			//check if user has already voted, determined by unique content cookie
			if (isset($_COOKIE["voted_".$unique_content_id]))
			{
				header('HTTP/1.1 500 Already Voted this Content!'); //cookie found, user has already voted
				exit(); //exit script
			}

			//get vote_up value from db using unique_content_id
			$result = mysqli_query($sql_con,"SELECT vote_down FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
			$get_total_rows = mysqli_fetch_assoc($result);
			
			if($get_total_rows)
			{
				//found record, update vote_down the value
				mysqli_query($sql_con,"UPDATE voting_count SET vote_down=vote_down+1 WHERE unique_content_id='$unique_content_id'");
			}else{
				
				//no record found, insert new record in db
				mysqli_query($sql_con,"INSERT INTO voting_count (unique_content_id, vote_down) value('$unique_content_id',1)");
			}
			
			setcookie("voted_".$unique_content_id, 1, time()+7200);  // set cookie that expires in 2 hour "time()+7200".
			echo ($get_total_rows["vote_down"]+1);//display total disliked votes
			break;	
		
		##### respond votes for each content #########		
		case 'fetch':
			//get vote_up and vote_down value from db using unique_content_id
			$result = mysqli_query($sql_con,"SELECT vote_up,vote_down FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
			$row = mysqli_fetch_assoc($result);
			
			//making sure value is not empty.
			$vote_up 	= ($row["vote_up"])?$row["vote_up"]:0; 
			$vote_down 	= ($row["vote_down"])?$row["vote_down"]:0;
			
			//build array for php json
			$send_response = array('vote_up'=>$vote_up, 'vote_down'=>$vote_down);
			echo json_encode($send_response); //display json encoded values
			break;

	}

}
?>

desculpaaa... ja ia colocar já


o SISTEMA QE TO FAZENDO É ASSIM

 

PESSOA POSTA O TEXTO DELA.. AI A PESSOA VOTA SE GOSTOU OU NÃO.. E SEMPRE QUANDO VOTO..O VOTO VAI PARA O PRIMEIRO TEXTO QE A PESSOA POSTO..

 

OUTRO CODIGO INDEX.PHP

<?php require_once('Connections/conec.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO voting_count (texto) VALUES (%s)",
                       GetSQLValueString($_POST['texto'], "text"));

  mysql_select_db($database_conec, $conec);
  $Result1 = mysql_query($insertSQL, $conec) or die(mysql_error());

  $insertGoTo = "noticia.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sin título</title>

</head>

<body>
<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
  <table align="center">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Texto:</td>
      <td><input type="text" name="texto" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"> </td>
      <td><input type="submit" value="Insert record" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1" />
</form>
<p> </p>
</body>
</html>

NOTICIA.PHP

<?php require_once('Connections/conec.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_conec, $conec);
$query_Recordset1 = "SELECT texto, vote_up, vote_down FROM voting_count";
$Recordset1 = mysql_query($query_Recordset1, $conec) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sin título</title>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	
	//####### on page load, retrive votes for each content
	$.each( $('.voting_wrapper'), function(){
		
		//retrive unique id from this voting_wrapper element
		var unique_id = $(this).attr("id");
		
		//prepare post content
		post_data = {'unique_id':unique_id, 'vote':'fetch'};
		
		//send our data to "vote_process.php" using jQuery $.post()
		$.post('vote_process.php', post_data,  function(response) {
		
				//retrive votes from server, replace each vote count text
				$('#'+unique_id+' .up_votes').text(response.vote_up); 
				$('#'+unique_id+' .down_votes').text(response.vote_down);
			},'json');
	});

	
	
	//####### on button click, get user vote and send it to vote_process.php using jQuery $.post().
	$(".voting_wrapper .voting_btn").click(function (e) {
	 	
		//get class name (down_button / up_button) of clicked element
		var clicked_button = $(this).children().attr('class');
		
		//get unique ID from voted parent element
		var unique_id 	= $(this).parent().attr("id"); 
		
		if(clicked_button==='down_button') //user disliked the content
		{
			//prepare post content
			post_data = {'unique_id':unique_id, 'vote':'down'};
			
			//send our data to "vote_process.php" using jQuery $.post()
			$.post('vote_process.php', post_data, function(data) {
				
				//replace vote down count text with new values
				$('#'+unique_id+' .down_votes').text(data);
				
				//thank user for the dislike
				alert("Thanks! Each Vote Counts, Even Dislikes!");
				
			}).fail(function(err) { 
			
			//alert user about the HTTP server error
			alert(err.statusText); 
			});
		}
		else if(clicked_button==='up_button') //user liked the content
		{
			//prepare post content
			post_data = {'unique_id':unique_id, 'vote':'up'};
			
			//send our data to "vote_process.php" using jQuery $.post()
			$.post('vote_process.php', post_data, function(data) {
			
				//replace vote up count text with new values
				$('#'+unique_id+' .up_votes').text(data);
				
				//thank user for liking the content
				alert("Thanks! For Liking This Content.");
			}).fail(function(err) { 
			
			//alert user about the HTTP server error
			alert(err.statusText); 
			});
		}
		
	});
	//end 
	
	
	
});


</script>
<style type="text/css">
<!--
.content_wrapper{width:500px;margin-right:auto;margin-left:auto;}
h3{color: #979797;border-bottom: 1px dotted #DDD;font-family: "Trebuchet MS";}

/*voting style */
.voting_wrapper {display:inline-block;margin-left: 20px;}
.voting_wrapper .down_button {background: url(images/thumbs.png) no-repeat;float: left;height: 14px;width: 16px;cursor:pointer;margin-top: 3px;}
.voting_wrapper .down_button:hover {background: url(images/thumbs.png) no-repeat 0px -16px;}
.voting_wrapper .up_button {background: url(images/thumbs.png) no-repeat -16px 0px;float: left;height: 14px;width: 16px;cursor:pointer;}
.voting_wrapper .up_button:hover{background: url(images/thumbs.png) no-repeat -16px -16px;;}
.voting_btn{float:left;margin-right:5px;}
.voting_btn span{font-size: 11px;float: left;margin-left: 3px;}

-->
</style>

</head>

<body>
<table border="1">
  <tr>
    <td>texto</td>
    <td>vote_up</td>
    <td>vote_down</td>
  </tr>
  <?php do { ?>
    <tr>
      <td><?php echo $row_Recordset1['texto']; ?></td>
      <td colspan="2">
      <div class="content_wrapper">
       <!-- voting markup -->
        <div class="voting_wrapper" id="1001">
            <div class="voting_btn">
                <div class="up_button"> </div><span class="up_votes">0</span>
            </div>    
              <div class="voting_btn">
                <div class="down_button"> </div><span class="down_votes">0</span>
            </div>
            </div>
            </td>
    </tr>
    <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Aqui:

header(sprintf("Location: %s", $insertGoTo));

Esse é o código executado de redirecionamento após votar.

 

É só mudar para a página que você gostaria.

 

Exemplo:

header("Location: paginateste.php");

Compartilhar este post


Link para o post
Compartilhar em outros sites

Maykel o amigo obg por responder.. mais o oq estou tentando resolver é assim..

 

a pessoa votou certo? ok ai ela vota de novo os votos vão tudo para o primeiro texto..

 

exemplo

 

TEXTO|VOTO UP| VOTO DOWN

OI |2 | 0

XAU | |0

 

QUANDO EU VOTO NO XAU ELE VOTA NO OI


É ALGUMA COISA QE TA LIMITANDO NÃO SEI.. PORQ VOU VOTAR NO XAU O VOTO VAI PRO OI

Compartilhar este post


Link para o post
Compartilhar em outros sites

Nossa, digite direito cara (sem maiúsculos, com pontuação ao menos entendível), tá MUITO COMPLICADO de ler.

 

Eu entendi VOLTO ao invés de voto, então esquece o que te disse no post #4.

 

Verifique se $unique_content_id está vindo com o ID certo do texto.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Maykel eu não manjo de php.. poxaa me ajuda nessa parada ai, so queria "QUERO" isso.

 

Acho qe o erro está aq

<?php
	####### db config ##########
	$db_username = 'root';
	$db_password = '';
	$db_name = 'teste';
	$db_host = 'localhost';
	####### db config end ##########

if($_POST)
{
		
	### connect to mySql
	$sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');

	//get type of vote from client
	$user_vote_type = trim($_POST["vote"]);
	
	//get unique content ID and sanitize it (cos we never know).
	$unique_content_id = filter_var(trim($_POST["unique_id"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
	
	//Convert content ID to MD5 hash (optional)
	$unique_content_id = hash('md5', $unique_content_id);
	
	//check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    } 
	

	switch ($user_vote_type)
	{			
		
		##### User liked the content #########
		case 'up': 
			
			
			
			//get vote_up value from db using unique_content_id
			$result = mysqli_query($sql_con,"SELECT vote_up FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
			$get_total_rows = mysqli_fetch_assoc($result);
			
			if($get_total_rows)
			{
				//found record, update vote_up the value
				mysqli_query($sql_con,"UPDATE voting_count SET vote_up=vote_up+1 WHERE unique_content_id='$unique_content_id'");
			}else{
				//no record found, insert new record in db
				mysqli_query($sql_con,"INSERT INTO voting_count (unique_content_id, vote_up) value('$unique_content_id',1)");
			}
			
			setcookie("voted_".$unique_content_id, 1, time()+7200); // set cookie that expires in 2 hour "time()+7200".
			echo ($get_total_rows["vote_up"]+1); //display total liked votes
			break;	
		
		##### User disliked the content #########
		case 'down': 
			
			//check if user has already voted, determined by unique content cookie
			if (isset($_COOKIE["voted_".$unique_content_id]))
			{
				header('HTTP/1.1 500 Already Voted this Content!'); //cookie found, user has already voted
				exit(); //exit script
			}

			//get vote_up value from db using unique_content_id
			$result = mysqli_query($sql_con,"SELECT vote_down FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
			$get_total_rows = mysqli_fetch_assoc($result);
			
			if($get_total_rows)
			{
				//found record, update vote_down the value
				mysqli_query($sql_con,"UPDATE voting_count SET vote_down=vote_down+1 WHERE unique_content_id='$unique_content_id'");
			}else{
				
				//no record found, insert new record in db
				mysqli_query($sql_con,"INSERT INTO voting_count (unique_content_id, vote_down) value('$unique_content_id',1)");
			}
			
			setcookie("voted_".$unique_content_id, 1, time()+7200);  // set cookie that expires in 2 hour "time()+7200".
			echo ($get_total_rows["vote_down"]+1);//display total disliked votes
			break;	
		
		##### respond votes for each content #########		
		case 'fetch':
			//get vote_up and vote_down value from db using unique_content_id
			$result = mysqli_query($sql_con,"SELECT vote_up,vote_down FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
			$row = mysqli_fetch_assoc($result);
			
			//making sure value is not empty.
			$vote_up 	= ($row["vote_up"])?$row["vote_up"]:0; 
			$vote_down 	= ($row["vote_down"])?$row["vote_down"]:0;
			
			//build array for php json
			$send_response = array('vote_up'=>$vote_up, 'vote_down'=>$vote_down);
			echo json_encode($send_response); //display json encoded values
			break;

	}

}
?>

acho qe está em alguma coisa ai, porq como te disse todas vez qe Voto ele sempre Vota no OI como dei o exemplo..

Compartilhar este post


Link para o post
Compartilhar em outros sites

Maykel ta assim...

 

VOTE_PROCESS

//get vote_up value from db using unique_content_id
			$result = mysqli_query($sql_con,"SELECT vote_up FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
			$get_total_rows = mysqli_fetch_assoc($result);

é alguma dessas linhas

//get vote_up value from db using unique_content_id
			$result = mysqli_query($sql_con,"SELECT vote_up FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
			$get_total_rows = mysqli_fetch_assoc($result);
			
			if($get_total_rows)
			{
				//found record, update vote_up the value
				mysqli_query($sql_con,"UPDATE voting_count SET vote_up=vote_up+1 WHERE unique_content_id='$unique_content_id'");
			}else{
				//no record found, insert new record in db
				mysqli_query($sql_con,"INSERT INTO voting_count (unique_content_id, vote_up) value('$unique_content_id',1)");
			}

ja mudei pra 2, tirei o LIMIT e nadaaa

Compartilhar este post


Link para o post
Compartilhar em outros sites

Cara, como te disse e vc não leu: Provavelmente o $unique_content_id está vindo com o valor que você não gostaria.

 

Use var_dump para ver o valor recebido de $unique_content_id

Veja se $_POST['unique_id'] não está recebendo sempre o mesmo valor, independente de qual você queira alterar. O erro está aí.

Compartilhar este post


Link para o post
Compartilhar em outros sites

oloco.. Dedas fala assim não.. a oloco só qeria arrumar isso :/

 

Dedas me ajuda ai por favor..

 

 

então mudei o id ele vota em todas as frase.. exemplo

 

TEXTO|VOTOUP|VOTODOWN

OI |1 |

XAU |1 |

BEM |1 |

 

QUANDO VC VOTA NO "bem" ele vota no oi e no xau tbm..

ele estava assim:

 

<div class="voting_wrapper" id="1001">

 

mudei para :

 

<div class="voting_wrapper" id="xxxx">

 

Codigo:

<body><table border="1"><div class="content_wrapper">  <tr>    <td>texto</td>    <td>vote_up</td>    <td>vote_down</td>  </tr>  <?php do { ?>    <tr>      <td><?php echo $row_Recordset1['texto']; ?></td>      <td colspan="2">        <div class="voting_wrapper" id="1001">        <div class="voting_btn">          <div class="up_button"> </div><span class="up_votes">0</span>          </div>        <div class="voting_btn">          <div class="down_button"> </div><span class="down_votes">0</span>          </div>      </td>    </tr>    <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?></table><a href="index.php">< voltar</body>

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.