Setting time limit php - php

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.

Related

Delete row after x minutes in mysqli database and php

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

Update: I dont know why the time difference when less than 180 seconds still adds 10 in the user rating column

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();

Whats wrong in my php mysql counter script code?

I am writing a Php 5 and Mysql 5 page counter script. When a student having id as 'visitorid' visits a page having id 'pageid' (both int(11)) the page counter tries to log the visit in 'visitors' database. But counter is not updating in mysql db, instead the visit_counter int(4) turns to 0.Whats wrong with my code? visitdate is datetime.
<?php
$pageid = 101;
$visitorid = 234;
$sql = "SELECT * FROM visitors
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("Error 1.<br>".mysql_error());
$data = mysql_fetch_array($temp);
// visit_counter is a field in table
if(($data['visit_counter']) != NULL){
echo "Entery exists <br>";
// Tried below version also
$visit = " SET visit_counter = visit_counter+1";
//$visit_counter = $data['visit_counter'];
//$visit = " SET visit_counter = ".$visit_counter++ ;
// Valid SQL
// UPDATE `visitors`
// SET visit_counter = visit_counter+1
// WHERE pageid = 101 and visitorid=234
// This manual sql query updates in phpmyadmin
$sql = "UPDATE visitors ".$visit."
AND visitdate = NOW()
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("ERROR 3.<br>".mysql_error());
//No error is displayed on above query.
} else {
//first entry
$visit_count = "1";
$sql = "INSERT INTO visitors
(`pageid`,`visitorid`, `visitdate`, `visit_counter`)
VALUES ('".$pageid."','".$visitorid."', NOW(), '".$visit_count."')";
$temp = mysql_query($sql);
//first entry is inserted successfully
//and visit_counter shows 1 as entry.
}
?>
Can anyone tell me whats wrong with this code?
Oh! I got answer by myself. Sometimes just little errors make us go crazy..
I made a mistake in udate query.. rather than using and I should have user a comma instead. .. working well now!

Online Status for Multiple Users

I was able to do online status but works only for one user. When I login, it shows all users on users.php online even when they are offline.
Here is the Status Code:
session_start();
include_once 'db_connect.php' ;
if(isset($_SESSION['users'])) {
$setLogged= mysql_query("UPDATE `users` SET `lastlogin` = '$last' WHERE `id` = '".$_SESSION['users']."'") or die(mysql_error());
}
$last = strtotime(date('Y-m-d H:s'));
$loggedtime = time() - 300; // 5 minutes
if($last > $loggedtime) {
echo '<font color="green" size="3px">online</font>';
} else {
echo '<font color="red" size="3px">offline</font>';
}
?>
I need help on how to make it work for multiple users.
Thanks. ;)
You have to use something like this:
$query=mysql_query("SELECT id FROM users WHERE last_login>NOW()-INTERVAL 30 MIN");
while($array=mysql_fetch_assoc($query)){
//Do something with the id's or the info you get for user who have there last login
//in the last 30mins
}
As #Crisp says in the comment above your query for last_login should be updated too, you can use mysql now() function like this:
$setLogged= mysql_query("UPDATE `users` SET `lastlogin` = NOW() WHERE `id` = '".$_SESSION['users']."'") or die(mysql_error());
Note you have to stop using mysql_* as these functions are deprecated, start using PDO or mysqli

PHP works first time then fails

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)?

Categories