I'm working on a school project where I need to allow users to vote on pictures. Users can a picture up or down. It's the idea that they can change their vote anytime, but they can't undo their vote, so once they voted it's either up or down.
I've been trying some things but I can't seem to get it to work. It works when an user pressed an upvote for the first time, then the user is able to change his vote to a downvote. But when he tries to upvote again, nothing is happening this has been bugging me for a while now, I would appreciated any help.
Here is my code so far:
if (isset($_SESSION['loggedin'])) {
$result = mysql_query("SELECT * FROM user2pics WHERE picid = $id AND userid = $user");
if (mysql_num_rows($result) == 0) {
$votes_up = $cur_votes[0] + 1;
$resultaat = mysql_query("UPDATE pics SET likes = $votes_up WHERE picid = $id");
if ($resultaat) {
$query = mysql_query("INSERT INTO user2pics (picid, userid, vote) VALUES ($id, $user, 1)");
if ($query) {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
} elseif (!$query) {
echo "Failed!";
}
} elseif (!$resultaat) {
echo "Failed insert in pics!";
}
} else {
$row = mysql_fetch_array($result);
if ($row['vote'] == 0) {
$votes_down = $cur_votes[0] + 1;
$result = mysql_query("UPDATE pics SET likes = $votes_up WHERE picid = $id");
if ($result) {
$resultaat = $mysqli -> prepare("UPDATE user2pics SET vote = 1 WHERE picid = $id AND userid = $user");
$resultaat -> execute();
$effectiveVote = getEffectiveVotes($id);
if ($resultaat -> affected_rows == 1) {
echo $effectiveVote . " votes";
}
}
} else {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
}
}
} else {
echo "Please login first!";
}
} elseif ($action == 'vote_down'){
if (isset($_SESSION['loggedin'])) {
$result = mysql_query("SELECT * FROM user2pics WHERE picid = $id AND userid = $user");
if (mysql_num_rows($result) == 0) {
$votes_down = $cur_votes[1] + 1;
$resultaat = mysql_query("UPDATE pics SET dislikes = $votes_down WHERE picid = $id");
if ($resultaat) {
$query = mysql_query("INSERT INTO user2pics (picid, userid, vote) VALUES ($id, $user, 0)");
if ($query) {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
} elseif (!$query) {
echo "Failed to dislike!";
}
} elseif (!$resultaat) {
echo "Failed insert in pics!";
}
} else {
$row = mysql_fetch_array($result);
if ($row['vote'] == 1) {
$votes_down = $cur_votes[1] + 1;
$result = mysql_query("UPDATE pics SET dislikes = $votes_down WHERE picid = $id");
if ($result) {
$resultaat = $mysqli -> prepare("UPDATE user2pics SET vote = 0 WHERE picid = $id AND userid = $user");
$resultaat -> execute();
$effectiveVote = getEffectiveVotes($id);
if ($resultaat -> affected_rows == 1) {
echo $effectiveVote . " votes";
}
}
} else {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
}
}
} else {
echo "Please login first!";
}
}
$cur_votes is defined as:
$cur_votes = getAllVotes($id);
function getAllVotes($id) {
$votes = array();
$q = "SELECT * FROM pics WHERE picid = $id";
$r = mysql_query($q);
if (mysql_num_rows($r) == 1)//id found in the table
{
$row = mysql_fetch_assoc($r);
$votes[0] = $row['likes'];
$votes[1] = $row['dislikes'];
}
return $votes;
}
function getEffectiveVotes($id) {
/**
Returns an integer
**/
$votes = getAllVotes($id);
$effectiveVote = $votes[0] - $votes[1];
return $effectiveVote;
}
You're duplicating functionality by storing 'likes' in two places.
I didn't look at your weak entity (table for users and votes) so let's assume it will have three fields: user_id, item_id and vote TINYINT. Primary key on user_id and item_id so the same user can only have one vote per item.
Set vote to 1 or -1 depending on up or down, instead of storing likes in the item table, calculate total vote for an item dynamically like this:
SELECT SUM(vote) FROM user_votes WHERE item_id = ?;
If you only want positive votes, do this:
SELECT SUM(vote) FROM user_votes WHERE item_id = ? AND vote = 1;
When the user wants to record or change his vote, you can use REPLACE INTO syntax (thanks to Anigel for the suggestion -- I totally missed it) in order to store the user's new vote:
REPLACE INTO user_votes (user_id, item_id, vote) VALUES (?, ?, ?);
Related
When Inserting data into SQL it inserts two into rows, and I don't know why.
most probably of the if statement I added after the results you can find it as my comment:
// id_no update
And I used the select query two times to fetch the id and make it an auto-increment thing.
my table:
<?PHP
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
?>
<?PHP
if(isset($_POST['add_id']))
{
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if(mysqli_query($con,$sql))
{
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
}
else
{
echo "Record Faileddd";
}
if($result)
{
$success="Post has been added successfully";
} else
{
$error="Something went wrong!";
}
$id_no = '';
}
?>
You should check if $resultĀ is truthy to see if the insertion succeded (without running another query):
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if($result)
{
...
}
I'm current working on a live leader-board page and i am trying to add a live view counter to it. I am not getting and data sent to the database and its not reading from the database. I have checked the db connection and its working. I have checked the code in php tester and it has no errors.
Take a look and let me know what i missed, Thanks
class VisitorCounterReal {
var $sessionTimeInMin = 5; // time session will live, in minutes
function VisitorCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$this->cleanVisitors();
if ($this->visitorExists($ip))
{
$this->updateVisitor($ip);
} else
{
$this->addVisitor($ip);
}
}
function visitorExists($ip) {
$query = "SELECT * FROM counter WHERE ip = '$ip'";
$res = mysqli_query($connection, $query);
if (mysqli_num_rows($res) > 0)
{
return true;
} else
if (mysqli_num_rows($res) == 0)
{
return false;
}
}
function cleanVisitors()
{
$sessionTime = 30;
$query = "SELECT * FROM counter";
$res = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($res))
{
if (time() - $row['lastvisit'] >= $this->sessionTimeInMin * 60)
{
$dsql = "delete from counter where id = $row[id]";
mysqli_query($dsql);
}
}
}
function updateVisitor($ip)
{
$query = "UPDATE counter SET lastvisit = '" . time() . "' WHERE ip =
'$ip'";
mysqli_query($connection, $query);
}
function addVisitor($ip)
{
$query = "INSERT INTO counter(ip, lastvisit) ";
$query .= "VALUES('$ip', '" . time() . "') ";
mysqli_query($connection, $query);
}
function getAmountVisitors()
{
$query = "SELECT COUNT(id) FROM counter";
$res = mysqli_query($connection, $query);
$row = mysqli_fetch_row($res);
return $row[0];
}
function show()
{
echo '<h3>There is ' . $this->getAmountVisitors() . ' watching
online</h3>';
}
}
This is on the live leaderboard page below
<?php
$counter = new VisitorCounterReal; // make a new counter
//content here
$counter->show(); // show the counter
// and here
?>
i have a problem figuring out, how to roll the dice/s, so that the result/s will either do nothing or only UPDATE the selected users inventory.
<?php
if(isset($_SESSION['loggedin']))
{
include 'system/config.php';
//SESSION
$username = $_SESSION['loggedin'];
//selecting id from table users
$sql = "SELECT id FROM users WHERE username ='$username'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
//the user id from users
$user_id = $row['id'];
$sql = "SELECT user_id, size_kg, fish1, fish2, fish3, fish4, fish5, seaweed FROM inventory WHERE user_id='$user_id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$userId= $row['user_id'];
$fish1 = $row['fish1'];
$fish2 = $row['fish2'];
$fish3 = $row['fish3'];
$fish4 = $row['fish4'];
$fish5 = $row['fish5'];
$seaweed = $row['seaweed'];
//for debug
echo "$userId. id " . "$fish1 . fish1 <br>";
//$CatchProbability: dice roll for Catch Probability (ex: CatchProbability >= 30; echo You cought a $FishType(fish1, fish2, fish3, fish4, fish5, seaweed))
function rollcatch() {
return mt_rand(1,100);
}
echo rollcatch()." catch <br>";//for debug
//$FishType: dice roll for type of Fish (ex: $FishType(fish1) = 1-10 , $FishType(fish2) = 11-20, $FishType(fish4) = 31-40 $FishType(fish5) = 41-50, $FishType(seaweed) = 51-100)
function rolltype() {
return mt_rand(1,100);
}
echo rolltype()." type <br>";//for debug
function catchFish(){
if(rollcatch() < 30){
$rolltype = rolltype();
$result = "";
if($rolltype > 0 && $rolltype<10){
$result = "fish1";
}
else if($rolltype > 10 && $rolltype<=20){
$result = "fish2";
}
else if($rolltype > 20 && $rolltype<=30){
$result = "fish3";
}
else if($rolltype > 30 && $rolltype<=40){
$result = "fish4";
}
else if($rolltype > 40 && $rolltype<=50){
$result = "fish5";
}
else
{
$result="seaweed";
}
$sql = "UPDATE inventory SET $result = $result + 1 WHERE user_id='$userId'";
if(mysqli_query($conn, $sql)){
echo("You caught a $result");
}
}
else
{
echo("You caught nothing...");
}
}
catchFish(); //for debug
}
?>
Please, help me to debug, I get this error on successful catch:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ... on line 72
Line 72
<?
if(mysqli_query($conn, $sql)){
echo("You caught a $result");
}
?>
If I understood your question correctly:
if($CatchProbability <= 30) {
$FishType = rolltype();
if ($FishType <= 10) {
$sql = "UPDATE inventory SET fish1 = fish1 +1 WHERE user_id = '$userId'";
if(mysqli_query($conn, $sql))
{
echo " </br> You caught one Fish1.</br>";
}
}
echo 'You caught a '.$FishType.';
Not entirely sure I understood perfectly, but this code:
Checks if you caught a fish (30% chance)
Determines which fish you caught (10% chance for fish 1-5, 50% chance seaweed)
Adds 1 to the caught fish in the database
Outputs a message of which fish you caught
Hopefully this works for you
function catchFish(){
if(rollcatch() < 30){
$rolltype = rolltype();
$result = "";
if($rolltype > 0 && $rolltype<=10){
$result = "fish1";
}
else if($rolltype > 10 && $rolltype<=20){
$result = "fish2";
}
else if($rolltype > 20 && $rolltype<=30){
$result = "fish3";
}
else if($rolltype > 30 && $rolltype<=40){
$result="fish4";
}
else if($rolltype > 40 && $rolltype<=50){
$result="fish5";
}
else
{
$result="seaweed";
}
$sql = "UPDATE inventory SET $result = $result + 1 WHERE user_id='$user_id'";
if(mysqli_query($conn,$sql)){
echo("You caught a $result.");
}
}
else
{
echo("You caught nothing...");
}
}
I've already checked here on stackoverflow and searched on google, but couldn't find my answer. I've created a rating system Thumbs up and down, only members could vote on a article. When a member votes, sql is updating the row voteup/votedown. Now I've made a new table called vote I've got there 5 columns id, user, uID, ctitle, cID
So If a member who is logged in as for ex: Admin and he thumbs up the article for ex: I like coding SQL INSERT INTO the table which is called vote Admin to user the title into ctitle but at the same time he needs to update the table called post the row vote_up or vote_down
I'm only receiving the error: Failed to vote,
<?php
include 'config.php';
require_once 'core/init.php';
$user = new User();
$username = $user->data()->username;
function getAllVotes(mysqli $db, $id)
{
$votes = array();
if($q_13 = "SELECT * FROM post WHERE id = $id");
if($r_26 = $db->query($q_13));
if($r_26->num_rows==1)
{
$stem = $r_26->fetch_object();
$votes[0] = $stem->votes_up;
$votes[1] = $stem->votes_down;
}
return $votes;
}
function getEffectiveVotes(mysqli $db, $id)
{
$votes = getAllVotes($db, $id);
$effectiveVote = $votes[0] - $votes[1];
return $effectiveVote;
}
$id = $_POST['id'];
$action = $_POST['action'];
//current votes
$cur_votes = getAllVotes($db, $id);
//update votes
if($action=='vote_up')
{
$votes_up = $cur_votes[0]+1;
$q_13 = "UPDATE post SET votes_up = $votes_up WHERE id = $id";
$q_13 = "INSERT INTO vote WHERE user = '$username', cID = '$id'";
}
elseif($action=='vote_down')
{
$votes_down = $cur_votes[1]+1;
$q_13 = "UPDATE post SET votes_down = $votes_down WHERE id = $id";
$q_13 = "INSERT INTO vote WHERE user = '$username', cID = '$id'";
}
$r_26 = $db->query($q_13);
if($r_26)
{
$effectiveVote = getEffectiveVotes($db, $id);
echo $effectiveVote." Archers";
}
elseif(!$r_26)
{
echo "Failed to vote!";
}
?>
This query runs when I comment out the code above '}else{'. Have done so many like it and way more complex but I can't see where I'm tripping up.
(The page won't run like a syntax mistake. all vars match table)
Thanks.
Allen
if ($version == 'prem'){
$sql ="SELECT * FROM artistInfo WHERE user_id = '$user_id' AND artist_name = '$artist_name' ";
$res = mysql_query($sql);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_id = $row['artist_id'];
} else {
mysql_query("INSERT INTO artistInfo (user_id, artist_name) VALUES ('$user_id', '$artist_name')");
$row_num = mysql_insert_id();
$artist_id = $user_id."-".$row_num;
mysql_query("UPDATE artistInfo SET artist_id = '$artist_id' WHERE row_num = '$row_num' ");
}
}
}
You're missing the closing } for the while loop.
missing } for while loop
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_id = $row['artist_id'];
}
}
else {
I think that your last bracket got misplaced. you will also need to move the last } just before else
if ($version == 'prem'){
$sql ="SELECT * FROM artistInfo WHERE user_id = '$user_id' AND artist_name = '$artist_name' ";
$res = mysql_query($sql);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_id = $row['artist_id'];
}
} else {
mysql_query("INSERT INTO artistInfo (user_id, artist_name) VALUES ('$user_id', '$artist_name')");
$row_num = mysql_insert_id();
$artist_id = $user_id."-".$row_num;
mysql_query("UPDATE artistInfo SET artist_id = '$artist_id' WHERE row_num = '$row_num' ");
}
}