Simple PHP voting system

I have a simple application that allows users to post "problems" and then comment on them. I am trying to create a simple voting system so that users can "vote" for problems that, in turn, will push them above the list. I have some basic knowledge of PHP and everything still works, I just can't figure out how to make this work.

I followed the tutorial online and still on my problem.php page ...

if (isset($_GET['vote'], $_GET['id'])){ add_problem_vote($_GET['id]'], $_GET['vote']); } <a href="?vote=up&amp;id=<?php echo $problemID; ?>">Vote</a> 

And on my functions.php page ...

 function add_problem_vote($problemID, $vote){ $problemID = (int)$problemID; $vote = ($vote === 'up') ? '+' : '-'; $sql = "UPDATE `problems` SET `votes` = `votes` {$vote} 1 WHERE `id` = {$problem_id}"; mysql_query($sql); } 

All the fields in my table are definitely correctly named. I know that there are many things to consider, for example, re-voting after the session closes, but so far I have shown the idea that it should not be ideal. The moment the link is clicked, it is redirected to the page, but the voices do not change in the mysql table.

+6
source share
9 answers
 $sql = "UPDATE `problems` SET `votes` = `votes` ".$vote." 1 WHERE `id` = ".$problem_id; mysql_query($sql) or die(mysql_error()); 

Check what error do you get?

+1
source

This does not work because you did not establish a MYSQL connection to your database, I think.

For my PHP projects, I (re) use a class that I once wrote every time, wrapping all these functions, with proper error handling, etc.

Maybe you should think about something like this, or at least you need to add mysql_connect before executing the queries.

Hope this helps.

0
source

try the following:

 "UPDATE `problems` SET `votes` = `votes` ".mysql_real_escape_string($vote)." 1 WHERE `id` = ".mysql_real_escape_string($problem_id); 
0
source

Not quite sure about this, but:

 $problemID = (int)$problemID; 

should be:

 $problemID = intval($problemID); 

Whenever something stops working, I always add

 echo $sql; 

Before calling mysql_query (); this way I can copy and paste the result into the SQL browser and see if it is correct.

EDIT: There was a different look, and as someone had previously escaped the SQL statement, I thought it was worth mentioning to try:

 $sql = "UPDATE `problems` SET `votes` = `votes` {$vote} 1 WHERE `id` = {$problem_id}"; 

To:

 $sql = "UPDATE `problems` SET `votes` = `votes` {".$vote."} 1 WHERE `id` = {$problem_id}"; 

but if all the SQL works, then why not try:

 $sql = "UPDATE `problems` SET `votes` = `votes`+1 WHERE `id` = {$problem_id}"; 

since this is exactly what you are doing, then there is no need to pass the $ vote parameter.

Other simple debugging options:

 print_r($_POST); // to show all the POSTED variables from a form print_r($_GET); // to show all the parameters from the URL 

Bbloke

0
source

First the request is not correct

 $sql = "UPDATE `problems` SET `votes` = `votes` {$vote} 1 WHERE `id` = {$problem_id}"; 

Correction

 $sql = "update `problems` set `votes` = '$vote' where `id` = '$problem_id'"; 

I suggest a different way. Make a table of votes with these columns: - user (user identifier) ​​- question (identifier of the thing to be voted) - vote (or number (example: from 0 to 4) or option (a, b, c ...))

primary key = user question

now you can easily insert / update voting

 mysql_query("replace into votes values ( $userid, $question, $vote )"); 

DONE! and you can easily get avg (if you chose the number of votes) or the number of votes (if you have options)!

0
source

I apologize for my poor English. I hope you understand this :) Therefore, for the first it is better to use mysqli or pdo. And if you create a new table for voting, you will have more opportunities to do this in the future (connect the ranks with users, the middle rows of specific users, check if the user voted earlier, ...)

Inspiration: User side (use jquery - ajax for sending):

 <a href="IDOFPROBLEM" title="VoteUp" class="voteUp">VoteUp</a> <script> $(document).ready(function() { $(".voteUp").click(function(e) { e.preventDefault(); var id = $(this).attr("href"); $.ajax({ type: "POST", //This is destination of PHP  url: "YOURVOTEUPFILE.php?vote=up", data: {id: id} }) .done(function(msg) { //msg contains data from PHP  so you can show message to user good or bad :) alert(msg); }); }); }); </script> 

Server side:

 final class manageVote { /** * Id of problem * @var int|string */ private $voteFor; /** * Id of user * @var int|string */ private $whoVote; /** * Mysqli * @var \mysqli */ private $database; /** * Construct - initialize variable * @param int|string $voteFor * @param int|string $whoVote * @param \mysqli $db */ public function __construct($voteFor, $whoVote, &$db) { $this->voteFor = $voteFor; $this->whoVote = $whoVote; $this->database = $db; } /** * Try to make vote * @param string $upOrDown "up" or "down" * @return boolean */ public function vote($upOrDown) { if (!$this->verifyIfUserCannote() || ($upOrDown != "up" && $upOrDown != "down")) return false; //Change database name to your name //Better solution is sql table for all ranks //And you need "whoVote" because I think one problem - one vote for one user /* * Table could be: * idvote PK NN AI * vote INT NN * idproblems FK NN * whoVote FK NN */ $sql = "INSERT INTO `DATABASENAME`.`problems` (`idproblems`, `vote`, `whoVote`) VALUES('" . $this->voteFor . "', '" . ($upOrDown == "up" ? 1 : -1) . "', '" . $this->whoVote . "')"; $query = $this->database->query($sql); if (!$query) return false; return true; } private function verifyIfUserCannote() { $sql = "SELECT COUNT(*) AS 'cnt' FROM `DATABASENAME`.`problems` WHERE `idproblems` = '" . $this->voteFor . "' AND `whoVote` = '" . $this->whoVote . "'"; $query = $this->database->query($sql); if (!$query) return false; $result = mysqli_fetch_array($query); return ($result["cnt"] == 0 ? true : false); } } if (isset($_GET["vote"])) { $voteClass = new manageVote($_POST["id"], $someYourIdentificatorWhoVote, $mysqliDatabaseReference); echo ($voteClass->vote($_GET["vote"]) == true ? "TRUE" : "FALSE"); } else echo "FALSE"; 

For the final voting rank, use the SQL SELECT SUM (voice) FROM ....... GROUP BY idProblems command

0
source

If you want to continue your first decision, the request should be:

 $sql = "update `problems` set `votes` = `votes` + 1 where `id` = '$problem_id'"; 
0
source

Please check the following errors:

  • Include .php functions in problem.php file
  • Use mysqli_query ($ sql) insted mysql_query ($ sql). Because it is out of date. You can also use PDO
  • Use the die (mysqli_error ($ connection_varible)) function to track sql errors.
0
source

Use an AND between the two data in the set-set function or just one of the data can be used for the set-set function.

  if (isset($_GET['vote'] && $_GET['id'])){ add_problem_vote($_GET['id]'], $_GET['vote']); } <a href="?vote=up&amp;id=<?php echo $problemID; ?>">Vote</a> function add_problem_vote($problem_id,$vote) { $query_select="select votes from problems where id='".$problem_id."'"; $query_run=mysql_query($query_select); if(mysql_num_rows($query_run)>0) { $vote_num=mysql_result($query_run,0,votes) if($vote==up) $vote_num=+$vote_num; else $vote_num=-$vote_num } $sql = "UPDATE `problems` SET `votes` = '$vote_num' WHERE `id` = '".$problem_id.'""; mysql_query($sql); } 
0
source

Source: https://habr.com/ru/post/915075/


All Articles