Upvote/Downvote System - php

I have the following PHP script:
<?php
$vote_type = $_GET['type'];
$book = $_GET['book'];
$id = $_GET['id'];
include 'pagehead.php';
$tracker_table = $book.'VoteTrack';
$username = $_SESSION['username'];
session_start();
if ($_SESSION['username'] == null) {
echo 'You must be logged in to vote';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
}
include 'mysqlserver.php';
$con = mysql_connect($mysql_host, $mysql_username, $mysql_password);
if (!$con){
die ('Failed to connect to the database');
}
mysql_select_db("a6595899_s", $con);
$data_query = "SELECT * FROM $book WHERE id=$id";
$lesson_data = mysql_query($data_query);
$lesson_array = mysql_fetch_assoc($lesson_data);
$vote_cop_query = "SELECT * FROM $tracker_table WHERE user='$username' AND id=$id";
$vote_cop_data = mysql_query($vote_cop_query);
$vote_cop = mysql_fetch_assoc($vote_cop_data);
if (mysql_num_rows($vote_cop_data) != 0 && $vote_type == 'up' && $vote_cop['has'] == 1) {
echo 'You have already upvoted this lesson.';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
} elseif (mysql_num_rows($vote_cop_data) != 0 && $vote_type == 'down' && $vote_cop['has'] == 2) {
echo 'You have already downvoted this lesson.';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
}
$vote_count = $lesson_array['votes'];
if ($vote_type == 'up') {
$vote_count++;
$has_type = 1;
} elseif ($vote_type == 'down') {
$vote_count--;
$has_type = 2;
} else {
die('Vote type not specified.');
}
$new_or = mysql_num_rows($vote_cop_data);
if ($new_or == 0) {
$track_query = "INSERT INTO $tracker_table (user, id, has)
VALUES ('$username', $id, $has_type)";
} else {
$track_query = "UPDATE $tracker_table SET has=$has_type WHERE user='$username' AND id=$id";
}
mysql_query($track_query);
//actually cast vote..
$update_query = "UPDATE $book SET votes=$vote_count WHERE id=$id";
mysql_query($update_query);
echo 'Your vote has been submitted!';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo'</a>';
?>
It's a very simple vote-up/and vote-down system. Unfortunately, it breaks down in certain scenarios. Let's say I'm reading a lesson that I think is good, so I vote it up. Later, I realize that the lesson is actually awful, so I downvote it. After I upvoted it the first time, the lesson had one point. After I downvote it, it has 0 again. Logic dictates that I should be able to downvote the lesson again, giving it -1 points. My code will not allow this, as my script simply says that the same action isn't allowed 2 times in a row.
What math do I use to fix this?

The problem is here where you're updating a user's activity after having downvoted their own upvote.
$track_query = "UPDATE $tracker_table SET has=$has_type WHERE user='$username' AND id=$id";
What you -should- be doing, is removing the record from the table instead of updating it, then go on to modify the score as you already are. That way, the next vote you do will be the 'first' vote you've done.
Alternatively, you could have a third vote_cop type called 'nullify' or 'revoke' or something then modify the vote cop accordingly.
See my suggestion below:
$hasVotedBefore = mysql_num_rows($vote_cop_data) != 0;
if ($hasVotedBefore) {
switch ($vote_cop_data['has']) {
case 0:
$vote_cop_type = 'revoked'; // Not really neccessary to do this, but just here for show.
break;
case 1:
$vote_cop_type = 'up';
break;
case 2:
$vote_cop_type = 'down';
break;
default:
break;
if ($vote_type == $vote_cop_type) { // We're here because we voted before and our new vote is the same as the old one.
if ($vote_type == 'up') {
echo 'You have already upvoted this lesson.';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
} elseif ($vote_type == 'down') {
echo 'You have already downvoted this lesson.';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
}
} else { // Were here because we've voted before, and our new vote is the opposite of the old vote.
// Update vote_cop row in the database so the 'has' column is 0 (value of a revoked vote)
// This way, for future votes, we know the user has voted before, but revoked their vote.
$track_query = "UPDATE $tracker_table SET has=0 WHERE user='$username' AND id=$id";
mysql_query($track_query);
}
} else { // We're here because we never voted before.
$track_query = "INSERT INTO $tracker_table (user, id, has) VALUES ('$username', $id, $vote_type)";
mysql_query($track_query);
}
// TODO: actually cast vote..

Related

Follow and Unfollow with Ajax works fine, but having issue with display

The ajax function for the follow and unfollow features on the webapp I'm developing works fine, but the issue is that when I click on either 'Follow' or 'Unfollow' button on any of the displayed list of my followers, the follow or unfollow button ONLY toggle without page refresh for the first follower on the displayed list of followers. If I click follow or unfollow on any other displayed followers except the first one on the list, I would have to refresh the page to see the follow/unfollow button changed.
In summary, clicking follow/unfollow button on any follower except the first on my displayed list of followers doesn't toggle the follow/unfollow button without page refresh.
PHP Code
$sql = "SELECT users.firstname, users.lastname, users.avatar, users.username FROM users INNER JOIN follows ON users.username=follows.user1 WHERE user2='$u' ORDER BY RAND()";
$result_select = mysqli_query($db_connect, $sql);
// Check if user has followers
$numrows = mysqli_num_rows($result_select);
if($numrows < 1){
echo '<div id="nav-follow">';
echo '<ul>';
echo '<li>'.''.'Followers'.''.'</li>';
echo '<li>'.''.'Following'.''.'</li>';
echo '</ul>';
echo '</div>';
echo '<div id="followerList" style="height:60px; text-align:center; vertical-align: middle; font-size:20px; color:white;">';
echo "I don't have any follower yet. If I start following others, they will also follow me.";
echo '</div></div>';
include_once("template_pageRight.php");
exit();
}
?><?php
echo '<div id="nav-follow">';
echo '<ul>';
echo '<li>'.''.'Followers'.''.'</li>';
echo '<li>'.''.'Following'.''.'</li>';
echo '</ul>';
echo '</div>'.'<br />';
// Fetch the user row from the query above
$row = array();
while ($row = mysqli_fetch_array($result_select))
$rows[] = $row;
foreach($rows as $row){
$followUsername = $row['username'];
?><?php
$following = false;
if($u == $log_username && $user_ok == true){
$follow_check = "SELECT id FROM follows WHERE user1='$log_username' AND user2='$followUsername' LIMIT 1";
if(mysqli_num_rows(mysqli_query($db_connect, $follow_check)) > 0){
$following = true;
}
} elseif($u != $log_username && $user_ok == true){
$follow_check = "SELECT id FROM follows WHERE user1='$log_username' AND user2='$followUsername' LIMIT 1";
if(mysqli_num_rows(mysqli_query($db_connect, $follow_check)) > 0){
$following = true;
}
}
?><?php
//$followUsername_Btn = "";
if($following == true){
$followUsername_Btn = '<button onclick="followUsernameToggle(\'unfollow\',\''.$followUsername.'\',\'followUsernameBtn\')">Unfollow</button>';
} elseif($followUsername != $log_username && $following == false && $user_ok == true) {
$followUsername_Btn = '<button onclick="followUsernameToggle(\'follow\',\''.$followUsername.'\',\'followUsernameBtn\')">Follow</button>';
} else {
$followUsername_Btn = '<button disabled>Me</button>';
}
?><?php
echo '<div id="followerList">';
echo '<a class="image" href="http://localhost:8080/app/user_audio.php?u='.$followUsername.'"><img src="user/'.$followUsername.'/'.$row['avatar'].'" alt="'.$followUsername.'">'.'<br />';
echo '<div id="fuserName">'.$row["firstname"].' '.$row["lastname"].'</a>'.'</div>';
echo '<span id="followUsernameBtn">'.$followUsername_Btn.'</span>';
echo '</div><br />';
}
?>
jQuery
function followUsernameToggle(type, user, elem) {
var conf = confirm("Please confirm.");
if (conf != true) {
return false;
}
//_(elem).innerHTML = 'please wait...';
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "follow_ok") {
_(elem).innerHTML = '<button onclick="followUsernameToggle(\'unfollow\',\'<?php echo $followUsername; ?>\',\'followUsernameBtn\')">Unfollow</button>';
} else if (this.responseText == "unfollow_ok") {
_(elem).innerHTML = '<button onclick="followUsernameToggle(\'follow\',\'<?php echo $followUsername; ?>\',\'followUsernameBtn\')">Follow</button>';
} else {
alert(this.responseText);
_(elem).innerHTML = 'Try again later';
}
}
};
xhttp.open("POST", "php_parsers/follow_system.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("type=" + type + "&user=" + user);
}
follow_system.php
<?php
$sql = "SELECT countrycode, mobile FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_connect, $sql);
if(mysqli_num_rows($query) > 0){
$row = mysqli_fetch_row($query);
$countrycode = $row[0];
$mobile = $row[1];
}
?><?php
$user = mysqli_real_escape_string($db_connect, $_POST['user']);
//$type = mysqli_real_escape_string($db_connect, $_POST['type']);
if($_POST['type'] == "follow" && isset($_POST['user'])){
$sql = "INSERT INTO follows (user1, user2, countrycode, mobile, datefollowed) VALUES ('$log_username','$user','$countrycode','$mobile',now())";
$query = mysqli_query($db_connect, $sql);
mysqli_close($db_connect);
echo "follow_ok";
exit();
} else if($_POST['type'] == "unfollow" && isset($_POST['user'])){
$sql = "DELETE FROM follows WHERE user1='$log_username' AND user2='$user' AND countrycode='$countrycode' AND mobile='$mobile'";
$query = mysqli_query($db_connect, $sql);
mysqli_close($db_connect);
echo "unfollow_ok";
exit();
}
?>
As I said, looking at the below picture, when I click Follow or Unfollow on FollowerB or C, the button doesn't toggle and I have to refresh the page to see the change in button from follow to unfollow and vice versa. But when I click on FollowerA which is at the top of the list, the button toggle without refresh.
Please I need help on why it's only the first follower on the list that works properly.
Follow_Unfollow_Picture

else statement content wont show?

Currently, my problem continues to persist as I want to display errors for existing accounts or a success message if the user creates a non-already existing account. For some odd reason, even if the sign-up is successful, it still display the errors? Is there something that I am doing wrong? The two if statements still run even if they are false??? I am not understanding...
if ($db_found) {
$uSQL = "SELECT * FROM login WHERE username = '$username'";
$uresult = mysql_query($uSQL);
$unum_rows = mysql_num_rows($uresult);
$eSQL = "SELECT * FROM login WHERE email = '$email'";
$eresult = mysql_query($eSQL);
$enum_rows = mysql_num_rows($eresult);
if ($unum_rows > 0) {
echo '<div class="error-message"><li>Username Already Exists</li></div>';
}
if ($enum_rows > 0) {
echo '<div class="error-message"><li>Email Already Exists</li></div>';
}
else {
echo '<div class="success-message">successfully</div>';
}
}
Personally I would combine the queries - and simplify the logic ( and escape your input )
if ($db_found) {
$sql = "SELECT * FROM login WHERE username = '{mysql_real_escape_string($username)}' OR email = '{mysql_real_escape_string($email)}'";
$result = mysql_query($sql);
if( mysql_num_rows($result) ){
while(false !== ($row = mysql_fetch_assoc($result))) {
if($row['username'] == $username ){
echo '<div class="error-message"><li>Username Already Exists</li></div>';
}
if($row['email'] == $email) {
echo '<div class="error-message"><li>Email Already Exists</li></div>';
}
}
}else{
echo '<div class="success-message">successfully</div>';
}
}
This might help you
$enum_rows = mysql_num_rows($eresult);
if($unum_rows < 1)
{
echo "Username is available";
}
else
{
echo '<div class="error-message"><li>Username Already Exists</li></div>';
}
if($enum_rows < 1)
{
echo '<div class="success-message">successfully</div>';
}
else
{
echo '<div class="error-message"><li>Email Already Exists</li></div>';
}

validation php not working?

The following is the email verification code for my site.
The verification url sent to the user's email is as follows:
http://www.mywebsite.com/valid.php?confr=2774405&userid=2
Extra notes :
1) key is a column in my database which gets a random value on registration.
2) if $verify == 1 and password_in_db=== user_entered_password, then login takes place in the login page.
<?php
include 'connect.php';
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$_GET['userid']'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1") {
echo "Link Expired . Go to our login page :";
} else {
if (isset($_GET["confr"]) && isset($_GET["userid"])) {
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2) {
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$_GET["userid"]' ;");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
} else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Code for connect.php
<?php
mysql_connect("host", "username", "pass"); //connects to the server
mysql_select_db("database_name"); //selects the database
?>
The problem is that it is giving me a blank screen .
i believe the error lies in the sql
when ever i use a "WHERE" statement i always define as a variable, try this
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
also, you have a semi colon in the insert sql
Try this.......
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
while ($details = mysql_fetch_assoc($query)){
$verify = $details['verify'];
$confirm2 = $details['key'];
}
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Note: insert statement has no where - as long as you dont use "insert into select..."
http://dev.mysql.com/doc/refman/5.1/de/insert.html

If statement returning true while it should be false.. i think

Well i got a very odd problem. Im trying to import the data from the WoW armory, and in the process add this information to my own database underneath a table called user.
Now im checking while adding new members also if all the information about the current members is still correct using (keep in mind fixing all the sql injection problems is something i will do after this):
#$json = file_get_contents("http://$region.battle.net/api/wow/guild/$realm/$guild?fields=members,achievements");
if($json == false)
{
throw new Exception("Failed To load infomation. check setup options");
}
$decode = json_decode($json, true);
foreach($decode['members'] as $p) {
$mrank = $p['rank'];
$mname = $p['character']['name'];
$mclass = $p['character']['class'];
$mrace = $p['character']['race'];
$mlevel = $p['character']['level'];
$mgender = $p['character']['gender'];
$check = mysql_query("SELECT * FROM user WHERE charactername='$mname'");
if($check == false)
{
die("Sql query failed");
}
if(mysql_num_rows($check) != 0)
{
if($mlevel !== $check['level'])
{
mysql_query("UPDATE user SET level='$mlevel' WHERE charactername='$mname'");
$uCount = $uCount + 1;
echo "level $mname<br />";
}
if($mclass !== $check['class'])
{
mysql_query("UPDATE user SET class='$mclass' WHERE charactername='$mname'");
$uCount = $uCount + 1;
echo "class $mname<br />";
}
if($mrace !== $check['race'])
{
mysql_query("UPDATE user SET race='$mrace' WHERE charactername='$mname'");
$uCount = $uCount + 1;
echo "race $mname<br />";
}
if($mgender !== $check['gender'])
{
mysql_query("UPDATE user SET gender='$mgender' WHERE charactername='$mname'");
$uCount = $uCount + 1;
echo "gender $mname<br />";
}
if($mrank !== $check['rank'])
{
mysql_query("UPDATE user SET rank='$mrank' WHERE charactername='$mname'");
$uCount = $uCount + 1;
echo "rank $mname<br />";
}
$pCount = $pCount + 1;
}
else
{
//add new user otherwise
$sql="INSERT INTO user (charactername, class, race, level, gender, rank) VALUES ('$mname','$mclass','$mrace','$mlevel','$mgender','$mrank')";
$nCount = $nCount + 1;
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
}
}
echo "$nCount new members added.<br />";
echo "$pCount member(s) already existed.<br />";
echo "$uCount member(s) got updated <br />";
But now is the problem, using this code the update part so all the:
if($mlevel !== $check['level'])
{
mysql_query("UPDATE user SET level='$mlevel' WHERE charactername='$mname'");
$uCount = $uCount + 1;
echo "level $mname<br />";
}
Run anyways, and i dont understand why. I compared the data and both are equal when echo'ed. So using !== should as far as i know only fire if they are not identical. With the current situation i have the update script running 800 times. And with that also literally updating all data in the user table 800 times. While this as far as i know should not be necessary.
Any help would be greatly appreciated.
You should try != if($mlevel != $check['level']) as !== checks if they are the same exact value and datatype and since you are retrieving both differently php may have assigned different datatypes to each
Or you can convert both $a =(int)$mlevel and $b = (int)$check['level'] then do a !==
While this probably is not the best way to do it, after finding out thanks to #MatthewBlancarte the query got a Null i decided to modify the code:
foreach($decode['members'] as $p) {
$mrank = $p['rank'];
$mname = $p['character']['name'];
$mclass = $p['character']['class'];
$mrace = $p['character']['race'];
$mlevel = $p['character']['level'];
$mgender = $p['character']['gender'];
$check = mysql_query("SELECT * FROM user WHERE charactername='$mname'");
while($row = mysql_fetch_array($check)){
$prank = $row['rank'];
$pname = $row['charactername'];
$pclass = $row['class'];
$prace = $row['race'];
$plevel = $row['level'];
$pgender = $row['gender'];
}
if($check == false)
{
die("Sql query failed");
}
if(mysql_num_rows($check) != 0)
{
if($mlevel != $plevel)
{
mysql_query("UPDATE user SET level='$mlevel' WHERE charactername='$mname'");
$uCount = $uCount + 1;
//echo "level $mname<br />";
}
Adding an extra query while loop with a mysql_fetch_array:
while($row = mysql_fetch_array($check)){
$prank = $row['rank'];
$pname = $row['charactername'];
$pclass = $row['class'];
$prace = $row['race'];
$plevel = $row['level'];
$pgender = $row['gender'];
Is what fixed it, comparing it to those variables works. Thank you all for the help. And before more people comment yes.. i will fix the sql injections.. >.>

No results returned for elseif PHP query

I have a database with a 'status' column which either reads 'active' or 'inactive'.
I'd like to return different text depending on whether the status is 'active' or 'inactive', and I'm using if... and elseif... for this.
If the status is 'active', the message is displaying perfectly. This also prompts the database to update the status field to 'inactive' - again, this is working perfectly.
But if I reload the page, using a key for which I know the status is 'inactive', nothing displays.
<?php
if (isset($_GET['key'])) {
$key = $_GET['key'];
include("db.php");
$download_query="SELECT * FROM sales WHERE key='$key'";
$download_result=#mysql_query($download_query);
$download_row=#mysql_fetch_array($download_result, MYSQL_ASSOC);
$productid=$download_row['productid'];
$datecreated=$download_row['datecreated'];
$dateaccessed=$download_row['dateaccessed'];
$status=$download_row['status'];
if ($status=="active") {
$download_updatestatus_query="UPDATE `sales` SET `status`='inactive' WHERE `key`='$key'";
$download_updatestatus_result=#mysql_query($download_updatestatus_query) or die (mysql_error());
echo "Go ahead and download file.";
}
else if ($status=="inactive") {
echo "You may have downloaded this before.";
}
}
else {
echo "Sorry, no key provided.";
}
?>
You have an extra } after your elseif. try:
else if ($status=="inactive") {
echo "You may have downloaded this before.";
}
else {
You suppose to make sure that mysql_query is not false and contains some results by running mysql_num_rows before you start fetching data.
Also passing $_GET value to MySQL Query without validation is very bad idea.
if (isset($_GET['key']))
{
//You have to make sure that provided value is safe to use in mysql query
$key = mysql_real_escape_string($_GET['key']);
include("db.php");
$download_query = "SELECT * FROM sales WHERE key='$key'";
$download_result = mysql_query($download_query);
// Check result
if (!$download_result)
die('Invalid query: ' . mysql_error());
if($download_result && mysql_num_rows($download_result) > 0)
{
$download_row = mysql_fetch_assoc($download_result);
$productid = $download_row['productid'];
$datecreated = $download_row['datecreated'];
$dateaccessed = $download_row['dateaccessed'];
$status = $download_row['status'];
if ($status == "active")
{
$download_updatestatus_query = "UPDATE `sales` SET `status`='inactive' WHERE `key`='$key'";
$download_updatestatus_result = mysql_query($download_updatestatus_query) or die (mysql_error());
echo "Go ahead and download file.";
}
else if ($status == "inactive")
{
echo "You may have downloaded this before.";
}
}
else
{
echo 'No results found';
}
}
else
{
echo "Sorry, no key provided.";
}

Categories