There is a script that triggers the code below
I want to disallow executing the script more than once per 24 hours.
I wanted this script to store the last visit time in a table against the user id in a database, then do a time calculation and back them out until the 24 hour expiry time.
Can someone explain how to do this? It would be greatly appreciated if someone could help me with this?
<?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$player = $_POST['Player'];
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
//---- This is the connection
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
mysql_select_db($dbname);
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
$query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
mysql_query($query1);
mysql_query($query2);
$query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
$result = mysql_query($query);
mysql_close($conn);
echo 'Done! Type /redeem in-game to get your diamonds.';
$ip=#$REMOTE_ADDR;
setcookie ("24Hourvote",$ip,time()+86400,'/',true,…
} else {
echo 'You have already voted today! Come back later...'; }
?>
EDIT: and could I make it so that it displays the time left until the user can vote again?
To me it looks like you already know what you have to do:
I wanted this script to store the last visit time in a table
against the user id in a database.Then do a time calculation and
back them out until the 24 hour expiry time.
So:
Forget about the cookie. It is stored on client side and can be manipulated.
Before count the vote check the [lastvisit] field of the current user.
If not set count the vote and set the [lastvisit] field in your table to the current date.
If set calculate the time span between now and the last vote. If bigger than 24 hours, count the vote and set the [lastvisit] field in your table to the current date.
Be aware of:
Manipulated parameters: $_POST['Player'];
SQL injections: VALUES ('".$player."', '".$input."')
If you have problems with one of these tasks then ask about the specific problem.
<?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
$ip = $_SERVER['REMOTE_ADDR'];
//---- This is the connection
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
mysql_select_db($dbname);
// Escape all user entered data always
$player = mysql_real_escape_string($_POST['Player']);
// Select time for this player if available
$query = "SELECT time FROM playersthatvoted WHERE player = '$player' ORDER BY time DESC LIMIT 0, 1";
$result = mysql_query($query);
if(mysql_num_rows($result) != 0)
{
$row = mysql_fetch_row($result);
$last_visit = $row[0];
$vote_allowed_time = $last_visit + 86400;
// Allowed to vote
if($time > $vote_allowed_time)
{
// Do whatever else you need to here ...
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
else
{
echo 'This player has already voted today! Come back later...';
}
}
else
{
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
$query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
mysql_query($query1);
mysql_query($query2);
$query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
$result = mysql_query($query);
mysql_close($conn);
echo 'Done! Type /redeem in-game to get your diamonds.';
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
} else {
echo 'You have already voted today! Come back later...'; }
?>
Note: Never trust the user input, always validate and escape the data.
Changed:
$player = $_POST['Player'];
to:
$player = mysql_real_escape_string($_POST['Player']);
Added:
// Select time for this player if available
$query = "SELECT time FROM playersthatvoted WHERE player = '$player' ORDER BY time DESC LIMIT 0, 1";
$result = mysql_query($query);
if($result)
{
$row = mysql_fetch_row($result);
$last_visit = $row[0];
$vote_allowed_time = $last_visit + 86400;
// Allowed to vote
if($time > $vote_allowed_time)
{
// Do whatever else you need to here ...
setcookie ("24Hourvote",$ip,time()+86400,'/');
}
else
{
echo 'This player has already voted today! Come back later...';
}
}
else
{
...
}
UPDATE
I would like to highlight the fact that as it stands anyone can enter the player name and try to vote for it and that does not necessarily mean the same user who clicks the vote button.
Additionally the IP address is not being used for any purposes, it may be an idea to use this for further permission/security checks.
Related
I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.
So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]
you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}
A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)
You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);
I am building a car parking application in which different users have different numbers of parking spots. This number is set by an administrator in a database. The user can input a numberplate which then will be added to a database as well. What I want is that when a user has occupied all the spots, that he will not be able to insert any more number plates.
However, now I have the following code at the moment:
if(isset($_POST['number_plate'])){
$numberPlate = $_POST['number_plate'];
$user_id = $_SESSION['id'];
$query = mysql_query("SELECT `parking_spots` FROM `login` WHERE `id` = ".$user_id." ");
$row = mysql_fetch_assoc($query);
$totalNumberOfSpots = $row['parking_spots'];
$occupiedNumberOfSpots = 0;
$sql = "INSERT INTO amsterdam (numberplate, user_id) VALUES ('$numberPlate','$user_id')";
if(mysql_query($sql))
{
echo 'numberplate added';
$occupiedNumberOfSpots++;
if($occupiedNumberOfSpots == $totalNumberOfSpots)
{
echo "There are no more spots avialable";
}
}
else
{
echo 'Something went wrong!';
}
}
But when I echo the $occupiedNumberOfSpots variable it keeps returning 1 and does not increment every time I add numberplate.
How can I solve this issue?
It is because You are running the same code each time You add a plate to your db.
this:
$occupiedNumberOfSpots = 0;
should be taken from db as well. I guess it should be like that:
$totalNumberOfSpots = 100; // for example
$occupiedNumberOfSpots = $row['parking_spots']; // taken from db
instead of:
$totalNumberOfSpots = $row['parking_spots'];
$occupiedNumberOfSpots = 0;
I am calculating AGE by DATE from DOB field, then I want to push it into AGE with correct age based on DOB . So As I debug The DOB calculating to AGE is works, but it cannot update AGE the code:
<?php
$servername = "localhost";
$username = "usernameexmaple";
$password = "passworking";
$dbname = "dbnameworking";
// Create connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id as ID, YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age
FROM regio_users";
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$newage = $row['age'];
$newid = $row['ID'];
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result2 = $conn->query($sql);
if ($result2){
echo "done"."<br>";
}
}
}
else {
echo "0 results";
}
$conn->close();
?>
It echos DONE for every ID but not updating anything at all.
You have used $result2 = $conn->query($sql); which is incorrect. You have to use $result2 = $conn->query($sql2); as $sql2 is the new query you formed.
This can be done with a single line SQL, rather than using PHP to loop through all the rows to only update the age:
UPDATE `regio_users` SET `age` = YEAR(CURRENT_TIMESTAMP) - YEAR(`dob`) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(`dob`, 5));
As saty pointed, use correct variable name.
Check if autocommit is on. If not, make sure you commit the data. Check for its syntax in PHP.
I have a database field which are
Appt_Datetime (which is call as DateTime in my table)
Svc_ID (which i call ApptType in my table)
I wanted the system to let the customer know that the datetime for the appt type is not available once someone else has book that slot.I have done a lot of research and trying out different codes but to no avail. I've seen answers on stackoverflow that uses PDO but im not so clear about it hence i'd like something to do with mysql. I have been stuck at with this at least few weeks now. Help
This is my call func:
$datetime = $_POST['DateTime'];
$appt = $_POST['ApptType'];
This is the query i last tried out but still is not working:
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if($row==1)
{
echo "Date in not available";
}
else if($row==0)
{
$query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn);
}
Hint:
change this to $result = mysql_query($query, $conn); to $result = mysql_query($vquery, $conn);
at the time you are using $conn you do not have $query it is $vquery:
$result = mysql_query($vquery, $conn);
And as suggested above in comments better use mysqli or PDO.
you can try this condition..
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
if($result = mysql_query($vquery, $conn)){
//$row = mysql_fetch_assoc($result);
if(mysql_num_row($result)>0)
{
echo "Date in not available";
}
else
{
/* $query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn); */
echo "insert";
}
}else{
echo mysql_error();
}
So as the title stated, I'm trying to insert data into 2 tables if the form passes a few conditions (the user is logged in, the user hasn't voted on that product before, all of the fields have been filled in).
It was inserting the data into both tables perfectly when the condition was just:
$sql = "SELECT productid FROM votes WHERE username='$username' LIMIT 1";
But I realized that if the user had voted on any of the products, their username would appear in the table and they would fail the condition without having voted on the product. So I just added:
$sql = "SELECT productid FROM votes WHERE username='$username' AND productid='$id' LIMIT 1";
and now if I try to submit data to the database, it always returns the 'Error inserting into votes table' message but doesn't return the mysql_error() and obviously doesn't insert a new row into the votes table, but strangely it does update the products table.
I just can't figure out what's going on, so if anyone could help me diagnose the problem, I'd really appreciate it! Here's the code:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['slider_surface'] !== "0" && $_POST['slider_edgewear'] !== "0" && $_POST['slider_centering'] !== "0" && $_POST['slider_corners'] !== "0"){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$slider_surface = $_POST['slider_surface'];
$slider_edgewear = $_POST['slider_edgewear'];
$slider_centering = $_POST['slider_centering'];
$slider_corners = $_POST['slider_corners'];
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
session_start();
$username = $_SESSION['username'];
//check if user has already voted
mysql_select_db('products');
$sql = "SELECT productid FROM votes WHERE username='$username' AND productid='$id' LIMIT 1";
$query = mysql_query( $sql, $conn );
$uname_check = mysql_num_rows($query);
if ($username){
if ($uname_check < 1) {
$sql = "INSERT INTO votes ".
"(username,productid,votesurface,voteedgewear,votecentering,votecorners,datetime) ".
"VALUES('$username','$id','$slider_surface','$slider_edgewear','$slider_centering','$slider_corners', now())";
$retval = mysql_query( $sql, $conn );
$id='';
// Make sure the _GET product ID is set, and sanitize it
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM products WHERE id='$id'") or die(mysql_error());
$product = mysql_fetch_array( $data );
$newvotecount = $product['votecount'] + 1;
$newsum_surface = $product['sumsurface'] + $slider_surface;
$newsum_edgewear = $product['sumedgewear'] + $slider_edgewear;
$newsum_centering = $product['sumcentering'] + $slider_centering;
$newsum_corners = $product['sumcorners'] + $slider_corners;
$sql = "UPDATE products SET votecount='{$newvotecount}', sumsurface='{$newsum_surface}', sumedgewear='{$newsum_edgewear}', sumcentering='{$newsum_centering}', sumcorners='{$newsum_corners}' WHERE id='$id'";
$retval2 = mysql_query( $sql, $conn );
if(! $retval){
die('Error inserting into votes table: ' . mysql_error());
}
else if(! $retval2){
die('Error inserting into products table: ' . mysql_error());
}
$grading_error = 'success';
mysql_close($conn);
} else
$grading_error = 'duplicateuser';
} else
$grading_error = 'nouser';
}
else
$grading_error = 'emptyfields';}
?>
There's a problem when inserting data to table, so there must be an error with the INSERT statement.
As #user2910809 says in previous comments, the sql evaluates as:
INSERT INTO votes (username,
productid,
votesurface,
voteedgewear,
votecentering,
votecorners,
datetime)
VALUES ('magmar',
'52',
'7',
'6',
'5',
'5',
now())
This sentence is syntactically correct. So, if there's an error, it must be with the inserted values.
As #user2910809 states on his comments, there's a UNIQUE key on username column, and it is what was throwing the error.
So the solution is to modify table's indexes to allow multiple rows with the same username.
Edit: as suggested in comments, the SQL to solve this problem was: ALTER TABLE votes DROP INDEX username;