I am creating a website in php. I have a database called database1 I have the tables cooldown and my_table The cooldown table contains the columns time(type Timestamp default value CURRENT_TIMESTAMP) and ip(type int(30) default value none). At the end of my code I have mysqli_query($conn, "DELETE FROM cooldown WHERE time < NOW() - INTERVAL 5 MINUTE"); which should delete the row after 5 minutes, but it doesn't delete the row. Could this be because the user gets redirected so the php script stops working? Or do I miss something else?
Code:
//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
//The value of $ip at this point would look something like: "192.0.34.166"
$ip = ip2long($ip);
//The $ip would now look something like: 1073732954
$query = mysqli_query($conn, "SELECT ip FROM cooldown WHERE ip = '$ip'");
$row = mysqli_fetch_array($query);
if ($row) {
//What page shall the bans be sent to?
header("Location: http://imnothere.epizy.com/cooldown.html"); //cooldownpage
exit();
} else {
$sql1= "SELECT links FROM my_table WHERE Type = 'spotify' ORDER BY RAND() LIMIT 1";
$result1 = $conn->query($sql1); //this actually runs the query on the DB, and comes back with a $result object
if($result1 === false) {
echo $conn->error();
}
$redirect = $result1->fetch_assoc()['links']; //this gets one row from the $result object, and then the 'links' column from that row.
header("Location: " . $redirect);
$sql = "INSERT INTO cooldown(ip, time) VALUES('$ip', NOW())";
$result = $conn->query($sql); //this actually runs the query on the DB, and comes back with a $result object
if($result === false) {
}
mysqli_query($conn, "DELETE FROM cooldown WHERE time < NOW() - INTERVAL 5 MINUTE");
}
Your SQL query won't delete the rows after 5 minutes, it will delete everything that is 5 minutes or older at the time of the request.
You're probably best moving that line of code to a separate file that is run by cron or setup an event in your db to do it say every minute or so.
U can with Cron job , supervisor or schedule time
Your SQL query almost as it
DELETE FROM cooldown WHERE time < NOW() - INTERVAL 5 MINUTE
If you want every five minutes, use either
*/5 * * * * fooo
Related
I have a user registration and login system that initially sets first date and time registered. Each time a user logs in i have a query that checks the time difference between the registered datetime and the current time now. if the difference in time is greater than or equal to 180seconds add 10 to the rating column of that user and reset current time of login as the new datetime/registered datetime, then redirect the user to index page.
If the time difference is less than 180 seconds just redirect the user to index page without adding a number to the rating table.
I have tried many codes did research on how to get this working all i see is cron job. i dont want to do this with cron job.
there has to be a way, please help. you guys need to save me.
This is what i have done
<?php
// This is part of the code
//$_SESSION['id'] = $id;
$_SESSION['email'] = $email;
date_default_timezone_set("Africa/Lagos");
// getting the time query difference
$sql1 = "SELECT TIMESTAMPDIFF(SECOND, date, NOW()) AS tdif FROM
users WHERE email='$email'";
$result = $con->prepare($sql1);
$result->execute();
$result->bind_result($tdif);
$result->fetch();
//var_dump($tdif);
if ($tdif >= 180) {
//following code suppose run once every 180seconds
//update user's page rank
$sql2 = "UPDATE users SET rating = rating + 10 WHERE email='$email'";
$result2 = $con->query($sql2) or die("Unable to select and run query");
//update last execution time
$sql3 = "UPDATE users SET date = NOW() WHERE email='$email'";
$result3 = $con->query($sql3) or die("Unable to select and run query");
}
//login me in
redirectToIndexPage();
// This Outputs Unable to select and run query
?>
This code just add 10 to the rating irrespective of the time difference all the time.
in other words it keeps adding 10 each time the user logs in which is suppose to happen only after 3mins(180seconds) from last login or registered datetime
Please help i know am getting something wrong.
As stated in the comments above you are not getting back a single value from your query as expected. The modified code below will do the same query and set your $tdif variable to a single value that will work in your if statement.
$sql1 = "SELECT TIMESTAMPDIFF(SECOND, date, NOW()) AS tdif FROM users WHERE email=?";
$result = $con->prepare($sql1);
$resylt->bind_param("s",$email);
$result->execute();
$result->bind_result($tdif);
$result->fetch();
if ($tdif >= 180) {
//update user's page rank
$sql2 = "UPDATE users SET rating = rating + 10 WHERE email='$email'";
$result2 = $con->query($sql2) or die("Unable to select and run query");
//update last execution time
$sql3 = "UPDATE users SET date = NOW() WHERE email='$email'";
$result3 = $con->query($sql3) or die("Unable to select and run query");
}
redirectToIndexPage();
I have a database with records to process. Number of records will vary. Too many records will cause my script to timeout but 15 records is a good safe number.
If my pseudo code is
//script begin
$sql = "SELECT id FROM table WHERE status = 0 LIMIT 0, 15";
runquery($sql);
foreach($rows as $row) {
//do things then run this sql:
$sql = "UPDATE table SET status = 1 WHERE id = {$theCurrentId};";
}
, can I achieve something like this at the end of the script:
$sql = "SELECT id FROM table WHERE status = 0";
runquery($sql);
if (rowcount() > 0) {
???? - something to call this script again as a new script
}
i.e. can I run this short script again if needed without it being counted in the timeout?
I want to make a mysql query after a few seconds the website user has performed an action on my website. I think I can do it with php sleep, but i don't know if it is the best way to do it. What are the options for doing that?
Thanks for your answers.
Edited:
The idea is: I have a lobby, where website registered users can join (When they join a mysql query is performed updating the info on their sql row, setting that they are connected to lobby number x, and on slot x, but they aren't joined to the server). When they join to the lobby i want to give them x time (suppose 5 minutes) to join a counter strike source server (This updates the user row setting that they are joined to the server). But, i want to kick them of the lobby (this is just updating again their row in the mysql database), if in those 5 minutes they haven't joined the server. I got all of this coded except the part of wait 5 minutes and check if they are connected.
The code is:
$PlayerSlot=mysql_real_escape_string($_POST['playern']);
$sID = mysql_real_escape_string($_POST['jsID']);
//Check if actual player is already in another lobby
$query = sprintf("SELECT `playern` FROM `WebsiteUsers` WHERE `userID`='%s'", mysql_real_escape_string($_SESSION['userID']));
$result = mysql_query($query, $con) or die("Error checking user state: ".mysql_error());
$row = mysql_fetch_row($result);
$playerPlaying = $row[0];
//Check if the slot is free
$query = "SELECT `".$PlayerSlot."` FROM `ServerPlayers`";
$result = mysql_query($query, $con);
$PlayerSlotFree = mysql_fetch_row($result);
if($playerPlaying == NULL && $PlayerSlotFree[0] == NULL) {
$query = "UPDATE `WebsiteUsers` SET `playern`='".$PlayerSlot."', `servern`='".$sID."' WHERE `userID`='".$_SESSION['userID']."'";
$result = mysql_query($query, $con) or die(mysql_error());
$query = "UPDATE `ServerPlayers`SET `".$PlayerSlot."`='".$_SESSION['userID']."', WHERE `serverID`='".$sID."'";
$result = mysql_query($query, $con) or die(mysql_error());
//Update Current Players
$query = "UPDATE `Servers` SET `serverPlayers`=serverPlayers + 1 WHERE `serverID`='".$sID."'";
$result = mysql_query($query, $con) or die(mysql_error());
//TO-DO Here Wait 5 minutes and perform another query
}
Use setTimeout() in javascript
// Wait for 3 Seconds then execute
setTimeout(function(){
// your action
}, 3000);
// In Every 3 Second Execute
setInterval(function(){
// your action
}, 3000);
I am trying to set time limit in reservation system. Such that Users must
have the ability to remove their bookings, but not before the lapse of 1 minute away from the time when the booking has been entered
<?php
require_once 'connection.php';
if(isset($_SESSION['book'])){
if (isset($_SESSION['book_time'])){
if (time()-$_SESSION['book_time']>= 60){
if (isset($_POST['delete'])){
$machineID = $_POST['machine_id'];
$starttime = $_POST['start_time'];
$qry = "DELETE FROM bookings where machine_id = '$machineID' AND start_time = '$starttime'";
$result = mysql_query($qry,$conn);
if ($result){
if(mysql_affected_rows()>0){
$message[] = 'Booking Deleted form DB';
}
}
}
}
}
}
?>
but it couldn't remove even after 1 min with this script....what could be possible problem
Possible problems:
$_SESSION['book'] or $_SESSION['book_time'] or $_POST['delete'] is NULL
$machineID contains not exists ID
$starttime contains wrong time or time in wrong format
Try to dump this variables. If they are ok try to run query manualy.
Basically what this does is makes it so after the user presses a button, they have to wait 2 minutes to press it again. When you press it the first time, it works, then if you press it again before 2 minutes, it says "please wait 2 minutes." but after 2 minutes, you can press it as many times as you like without the error, not what I want. Here is the code
<?php
if('sub') {
$client = $_SERVER['REMOTE_ADDR'];
$username="user";
$password="pass";
$database="db";
mysql_connect(localhost,$username,$password);
$time = strtotime("2 minutes");
$now = strtotime("now");
#mysql_select_db($database) or die( "Unable to select database");
$query = "SELECT Time FROM log WHERE IP='$client'";
$result= mysql_query($query);
$num=mysql_num_rows($result);
while($rows=mysql_fetch_array($result)){
$timestamp = $rows['Time'];
}
echo n;
echo $now;
echo t;
echo $timestamp;
if($now < $timestamp)
{
echo "<center><h2 style=\"color:red\" class=\"texts\" id=\"homeLink\">Please wait 2 minutes.</h2></center>";
}
else{
//some other code
$query1 = "INSERT INTO log VALUES ('$client','$time','$username')";
$query2 = "UPDATE `log` SET `Time`='$time' SET `Username`='$username' WHERE `IP`='$client'";
if($num == 0)
{
mysql_query($query1);
}
else
{
mysql_query($query2);
}
mysql_close();
}
?>
As you can see, if there is no row for the IP of the user, it makes a new one, if there is it will update it. After the first time, it no longer works. Hope someone can help. Thanks!
Your update statement is a bit off, so the update fails;
UPDATE `log` SET `Time`='$time' SET `Username`='$username' WHERE `IP`='$client'"
You should only use SET once, like this;
UPDATE `log` SET `Time`='$time', `Username`='$username' WHERE `IP`='$client'"
I'm pretty sure your database does not contain entries you think it contains. Can you check it (IPs and stuff on after button press)?