How to record one vote per user php - php

So I am trying to write a php script that records one vote increment per user. Voters a are presented with a list of prospective candidates then clicks once on their name.
Now on attempt of a second time i hope to get a notification allowing this action. Please help.
<?php
if(isset($_POST['vote']))
{
$sql3='INSERT INTO sessions (memberID, postid, email, voted) VALUES ("","", "", 1;)';
$result3 = mysqli_query($con, $sql3);
}
// $count = mysqli_num_rows($result2);
$candidate_name = null;
$vote = $_POST['vote'];
mysqli_query($con, "UPDATE tbCandidates SET candidate_votes=candidate_votes+1 WHERE position_id='$vote'");
// $count = mysqli_num_rows($result2);
if ( $count<1) {
//$sql3='INSERT INTO sessions (memberID, postid, voted) VALUES ("", memberbers.memberID,"1")';
//$result = mysqlI_query("select id from Users where username ='".$_SESSION['email']."'");
//$result = mysqli_query($con, $sql3);
// $count = mysqli_num_rows($result2);
} else {
echo"You have voted already";
}

Put a "unique" flag on your memberID column in your SQL table. In that case when you try to insert a new row with the same memberID, it will not work.
Then catch the SQL write fail, and display a message if it gets to it.

Related

Create a "Secret Santa" generator using MySQL and PHP

I am trying to create a Secret Santa system using a PHP page and a MySQL database to store the details so if someone forgets their match they can re-request it.
Step 1: I created a random number generator based on the number of people in the list in the database.
Count Function:
$maxSQL = "SELECT COUNT(id) as total FROM secretsanta";
$maxRS = mysqli_query($conn, $maxSQL);
$maxQuery = mysqli_fetch_array($maxRS);
$maxpersons = $maxQuery['total'];
Then the Random Number Generator:
$assigned = rand(1,$maxpersons);
Step 2: Test if the random number matches the persons own id and regenerate a new number if true.
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id);
Step 3: Write the paired id to the persons database record.
$assignSQL = "UPDATE secretsanta SET assigned = '".$assigned."' WHERE secretsanta.id = ".$id;
if (mysqli_query($conn, $assignSQL)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
The Problem: Now I need to check that other people aren't assigned to that person or otherwise some could miss out and others would get more than others.
I tried to implement a function that contained a query to test each record to see if that number already existed and was hoping to add it as a condition to perhaps a while or do while statement?
if (!function_exists('checkRandom')){
function checkRandom($funcid){
$Check_SQL = "SELECT assigned FROM secretsanta ORDER BY id ASC";
$Check_RES = mysqli_query($conn, $Check_SQL);
if (Check_RES) {
while ($CheckArray = mysqli_fetch_array($Check_RES, MYSQLI_ASSOC)) {
$CheckAsgn = $CheckArray['assigned'];
if ($funcid==$CheckAsgn) {return true;}else{return false;}
}
}
}
}
Then implement it into the do while statement like this:
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id||checkRandom($assigned));
No luck so far...HELP!.. please :)
P.S. I know there are websites that already do this, I just don't trust them to give out mine and family email address' if I can make my own private version myself.
Using your method, the first few assignments will be done with no problem, but imagine the last unassigned entry and how many times it will try a random number only to find the person with that id is already assigned..
I'm gonna give you another approach to your problem: for each user that you want to assign a santa to, make a new SELECT statement with a WHERE clause that lets you select only those users that are not assigned yet.
check out my code and see if that helps you. I just typed this and didnt test it so there could be some mistakes.
// load all unassigned users into an array
$unassignedUsers = [];
$query = "SELECT id, assigned FROM secretsanta WHERE assigned is NULL";
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedUsers[] = $row;
}
if(count($unassignedUsers) == 1){
echo 'There is only 1 unassigned user. Therefore he cannot be matched';
} else {
// for loop for each user in DB that is not assigned yet
//for ($i = 1;$i <= count($unassignedUsers); $i++){
$i = 0;
foreach($unassignedUsers as $user)
// if its the second-to-last iterations of the for-loop, check for legality of the last one
if(count($unassignedUsers) - $i == 1){
$lastUserID = $unassignedUsers[count($unassignedUsers)-1]['id'];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id = ".$lastUserID;
$res = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($res);
if ($rowcount){
// last user is still unassigned
$query = "UPDATE secretsanta SET assigned = '".$lastUserID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
} else {
// select all unassigned users
$unassignedIDs = [];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id <> ".$user['id'];
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedIDs[] = $row['id'];
}
// get a random id from $unassignedIDs
$randomIndex = rand(0, count($unassignedIDs)-1);
$randomID = $unassignedIDs[$randomIndex];
// assign $randomID to user
$query = "UPDATE secretsanta SET assigned = '".$randomID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
$i++;
}
}
last edit: refactored whole code so it is able to be run multiple times and only assigns new users who are not assigned yet.
Step 1 is dependent on have a contiguous set of ids for the people. Think what happens if '3' leaves the company and it hires 6 to replace them....1,2,4,5,6 ($maxpersons=5)
"Now I need to check" - no you are still trying to solve the problem by guessing then seeing if your guess worked. Use an algorithm which is always going to return a correct result. The method below requires the addition of a temporary field 'sequence' of type float.
mysqli_query($conn,"UPDATE secretsanta SET sequence=RAND()");
$first=false;
$prev=false;
$all=mysqli_query($conn, "SELECT * FROM secretsanta ORDER BY sequence, id");
while ($r=mysqli_fetch_assoc($all)) {
if (false===$first) {
$first=$r['id'];
} else {
save_pair($prev, $r['id']);
}
$prev=$r['id'];
}
save_pair($prev, $first);
(but with better error checking)

Make hit counter per user profile on PDO

I have a problem with this code for make a hit counter per user profile on PDO (MYSQL), on page loads not update and not show the counter, only text "Visits:", the value remains at "0".
$id = $profile_data['username'];
$statement = $db->query("SELECT `visits` FROM `users` WHERE id='$id'");
$record = $statement->fetchAll();
if(sizeof($record) != 0)
{
$counter = $record[0]['counter']++;
$db->exec("UPDATE `users` SET visits='$counter' WHERE id='$id'");
echo "Visits: " .$counter;
}
else
{
$db->exec("INSERT INTO `users` (id, visits) VALUES ('$id', 1)");
echo "Visits: 1";
}
Since you pulling the fields visits from the database, you need to change:
$counter = $record[0]['counter']++;
to:
$counter = $record[0]['visits']++;

fetch timestamp mysql value in $_SESSION

$qry = "SELECT user, TIME_FORMAT(last_login_time, '%H:%i') FROM login_attempts WHERE user = '".$username."'";
$result = mysql_query($qry,$this->connection);
if(!$result || mysql_num_rows($result) <= 0){
mysql_query ("INSERT INTO login_attempts(userid, user, attempts, last_login_time) VALUES('', '$username', '{$_SESSION['count']}', '{$_SESSION['login_time']}')");
}
else{
$row = mysql_fetch_assoc($result);
$_SESSION['login_time'] = $row["last_login_time"];
mysql_query ("UPDATE login_attempts SET attempts = '" .$_SESSION['count']."' WHERE user = '".$username."'");
}
In the above code I'm storing my $_SESSION['login_time'] value in 'login_attempts' table where the column name is 'last_login_time'.
Now I need to fetch this value and store it back in $_SESSION['login_time'] array so that I get to know when the last time user tried to enter. How shall I fetch this value???
The datatype of 'last_login_time' column is 'timestamp'.
You need to alias your TIME_FORMAT column in order to reference it.
SELECT user, TIME_FORMAT(last_login_time, '%H:%i') AS last_login_time ...
Also, why not UPDATE the login attempts to SET attempts = attempts + 1 ?

Posted results will not save to the mysql database, even when no record exists

I am using the following with a quiz I am making, it checks the table to see if the user has already posted the answer to the question and isn't hammering the submit button, the problem I am having is its not posting the info to the database for some odd reason. If I take out the if statement and the first database looking and just post the data it works fine, but when I check the result of the first query first, it doesn't appear to work, even if the user hasn't submitted an answer yet.
<?php
$quizID = $_GET['quiz'];
$userID = $_GET['user'];
$quizselectanswer = $_POST['quizselectanswer'];
$cf_created = date("y/m/d");
$questionID = $_POST['questionID'];
// Check to see if user answered question already
$result = mysql_query("SELECT questionID,userID FROM itsnb_chronoforms_data_answerquiz WHERE questionID='$questionID' AND userID='$userID' LIMIT 1") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
if (empty($row))
{
mysql_query("INSERT INTO itsnb_chronoforms_data_answerquiz (cf_created, questionID,quizselectanswer,quizID, userID)
VALUES ('$cf_created', '$questionID', '$quizselectanswer', '$quizID','$userID')")
or
die(mysql_error());
}else{
}
}
?>
My database looks like this itsnb_chronoforms_data_answerquiz cf_id, cf_uid, cf_created, cf_modified ,cf_ipaddress ,cf_user_id ,questionID, quizselectanswer, quizID ,userID.
Try like this it may help you
// Check to see if user answered question already
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_answerquiz WHERE questionID='$questionID' AND userID='$userID' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array($result);
if(!empty($row))
{
while($row){
//some statement
}
}else{
mysql_query('INSERT INTO itsnb_chronoforms_data_answerquiz (cf_created, questionID,quizselectanswer, quizID, userID)
VALUES ("'.$cf_created.'", "'.$questionID.'", "'.$quizselectanswer.'", "'.$quizID.'","'.$userID.'")') or die(mysql_error());
}
?>

Updating records If ipAddress and playerName match

At the moment im sending scores and data to my database from my flash game, though every level completed is a new record.
feilds are set out like l1Score,l2Score,l3Score
im trying to figure out how to update records if the field ipAddress and playerName match the current $varibles.
UPDATE highscores SET l2Score = '$l2Score' WHERE ipAddress = "$ipAddress" && playerName = '$playerName'
I was thinking somthing along these lines, but could someone point me in the right direction please!
First you want to perform a query to check if there is already a score in place for that user & IP.
$sql = "SELECT * FROM highscores WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
$result = mysql_query($sql, $con);
$row = mysql_fetch_assoc($result);
Now, if $row is empty then you want to insert a new record, else you want to update a previous record.
if($row == "")
{
$query = "INSERT INTO highscores (l2score, ipAdress, playerName) VALUES ('$l2score', '$ipAdress', '$playerName'";
} else {
$query = "UPDATE highscores SET l2Score = '$l2Score' WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
You may need to edit this to fit with the specific query that you need.

Categories