I want to compare two dates with each other to see if 10 minutes has passed.
This is the code that I've got but I can't quite figure out how to do it.
I get the first date from my table (which is saved as a timestamp, example: 2017-03-26 22:33:45) and then I want to compare it with the time that is right now.
$sql = "SELECT saved_time from table1 where email = '$email'";
$stmt = $conn->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch()) {
$savedTime = $row[0];
}
$now = time();
if (/*10 minutes has passed between saved time and now*/) {
echo "Your account is unlocked";
} else if (/*10 minutes hasn't passed*/) {
echo "Your account is locked";
}
Try This code:
$timezone = "Asia/Kolkata";// Select Timezone as of your Preference or MySQL Server Timezone
date_default_timezone_set($timezone);
$sql = "SELECT saved_time from table1 where email = :email";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $email));
while($row = $stmt->fetch()) {
$savedTime = $row[0];
}
// Uncomment below Line if $savedTime is in MySQL DATETIME Format
// $savedTime = strtotime($savedTime);
$now = time();
if (round(($now - $savedTime) / 60,2) >= 10){
echo "Your account is unlocked";
} elseif (round(($now - $savedTime) / 60,2) < 10){
echo "Your account is locked";
}
if $now = time(); #(this will generate a timestamp)
assuming $savedTime = $row[0]; is a MySQL date field, you can do
$savedTimeTimestamp= date("Y-m-d H:i:s", $savedTime);
...now 10 time 60 seconds is 10 minutes, so
if ($now > ($savedTimeTimestamp+600))
should do the job
If mysql solution is fine for you, then
select * from table T where TIMESTAMPDIFF(MINUTE,.saved_time,NOW()) > 10
If you need it in php, then
$db_time = $row['saved_time'];//as you have stored in timestamp already
$curr_time = strtotime(date('Y-m-d H:i:s'));
$diff = round(abs($db_time - $curr_time) / 60,2);
if($diff > 10)
Update
select now() as curr_time, saved_time from table where COND;
then in php
$diff = $curr_time-$saved_time;
if($diff > (10*60 ))
I am not sure whether this will work. But just an idea.
Related
I'm trying to create a visitor counter, when user visit the page it will record the time and the number of visitor. But when I refresh the page, my database will be like this:
The code that I do is:
if (empty($counter)){
$counter = 1;
$total = 1;
$time = date('Y-m-d H:i:s');
$sql1 = "INSERT INTO humancount(counter, time, totalHumanCount) VALUES ('$counter', '$time', '$total)";
$result1 = mysqli_query($con, $sql1);
}
//date_default_timezone_set('Asia/Kuala_Lumpur');
$date1 = strtotime("now");
$date2 = strtotime("tomorrow");
echo date("Y-m-d H:i:s", $date1);
echo "<br>";
echo date("Y-m-d H:i:s", $date2);
if ($date1 < $date2){
$plusCounter = $counter + 1;
$plusTotal = $total + 1;
$nextTime = date('Y-m-d H:i:s');
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal'";
$result2 = mysqli_query($con, $sql2);
}
I was expecting that it will record the time of the user visit by every row.
This line of code is overwriting every row in the table with the current counter update:
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal'";
you should instead insert a new row for each new visitor.
Also, this will always be true:
if ($date1 < $date2)
so you can remove the if statement.
You can do something like this:
//first fetch the last values from the database
$sql0 = "SELECT counter, totalHumanCount FROM humancount ORDER BY time DESC LIMIT 1";
$result = mysqli_query($con, $sql0);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$counter = $row['counter'] + 1;
$total = $row['totalHumanCount'] + 1;
} else {
$counter = 1;
$total = 1;
}
//date_default_timezone_set('Asia/Kuala_Lumpur');
$time = date('Y-m-d H:i:s');
$sql1 = "INSERT INTO humancount(counter, time, totalHumanCount) VALUES ('$counter', '$time', '$total)";
$result1 = mysqli_query($con, $sql1);
Use Where condition in UPDATE query. as per your query every time it will update all rows in table 'humancount'. so add UserID column for unique row and then update row for selected user.
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal' WHERE userID = ?";
For some reasons, the following select statement does not execute in mariadb 10 but executes well in mariadb 5.5. In 5.5 it picks values from a database in those two time ranges. Fails to pick any on 10. with the same database. What could the problem be? Anyone?
Thank you.
$_SESSION['post-data'] = $_POST;
$t1 = $_SESSION['post-data']['t1'];
$t2 = $_SESSION['post-data']['t2'];
$time1 = mysqli_real_escape_string($conn, $t1);
$time2 = mysqli_real_escape_string($conn, $t2);
$sql = "SELECT DISTINCT msisdn FROM customer WHERE DATE_FORMAT(time_paid,'%Y-%c-%e')
BETWEEN ADDDATE('$time1',INTERVAL 0 HOUR)
AND ADDDATE('$time2',INTERVAL '23:59' HOUR_MINUTE)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "Number of Recipients: "; echo "$result->num_rows <br> <br>";
// output data of each row
while($row = $result->fetch_assoc()) {
$mobilenumber[] = $row['msisdn'];
}
} else {
echo "No Contacts to Display";
}
$mob_numbers = implode(", " , $mobilenumber);
echo "$mob_numbers";
$_SESSION['numbers'] = $mob_numbers;
Don't bother using DATE_FORMAT assuming time_paid is DATE or DATETIME or TIMESTAMP. That will let you use an index. Then add this composite INDEX(time_paid, msisdn); it will be helpful and "covering".
Then change the BETWEEN to:
SELECT DISTINCT msisdn
FROM customer
WHERE time_paid >= $time1
AND time_paid < $time2 + INTERVAL 1 DAY
I'm am writing a PHP program that will get all of the dates for the current work week (excluding Monday). My code is as follows:
//Get Year
$sql = "SELECT YEAR(CURDATE()) AS CurYear";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$curyear = $row['CurYear'];
//Get Week
$sql = "SELECT WEEK(CURDATE()) AS CurWeek";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$curweek = $row['CurWeek'];
//Get Date of Tuesday
$sql = "SELECT STR_TO_DATE('$curyear$curweek Tuesday', '%X%V %W') AS TueDate";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$tuedate = $row['TueDate'];
It works and will return the date of this Tuesday, but is there a more efficient way of doing this, and moreover doing it for the following 3 days?
As explained here: How to find the day of week from a date using PHP?
you can use the date command:
$time = time(); // present time
$day = 3; //the day of the week we are looking for 0: sunday, 1 monday and so on
$dayofweek = date('w', $time); //current day week number
$result = date('Y-m-d', strtotime(($day - $dayofweek).' day', $time));
I'm not sure if you have a requirement of using MySQL, but I would do this in PHP directly. Below is a sample of how you could approach it. Once the variable $TuesTS is set, you can figure out the next day by adding (24*60*60) or 86400 to it, which is the number of seconds in a day.
<?php
$ts = time();
$todayNum = date('N');
if ( ($todayNum >= 2) && ($todayNum<=5)){
$offset = $todayNum - 2; // number of days after Tuesday;
$TuesTS = $ts-($offset*24*60*60);
echo "Tuesday : ".date('Y-m-d', $TuesTS);
}
?>
OK! So, I have a page where I'm trying to pull a list of records from the database with dates < 30 days from expiration.
Now, the tricky part is - that the date format is in "yyyy-mm-dd hh:mm:ss"
Here's my code:
$Today = date("Y-m-d h:i:s");
if ($result = $mysqli->query("SELECT * FROM table WHERE DATEDIFF(ExpireDate, '$Today') < 30 ORDER BY `StartDate` ASC"))
{
while($row = mysqli_fetch_array($result))
{
//show records
//this type of query usually works when I'm NOT doing stuff with dates
}
mysqli_close($mysqli);
}
When I try to pull just records without any date/time conditions, it gives me the entire list of records, but when I want to see the those conditions, it doesn't display anything.
How do I show the records that are 30 days from expiration?
I SHOULD NOTE - that this is for internal use, only, and that there is no access from the outside world.
(I just wanted something simple for internal records keeping)
I've even tried this:
select * from table where some_date < curdate() - interval 30 day
and failed miserably... thoughts?
Just let the > & < operators take care of it
$Today = date("Y-m-d h:i:s");
$ExpiresFromToday= date("Y-m-d h:i:s", strtotime("+30 days"));
if ($result = $mysqli->query("SELECT * FROM `table` WHERE (`ExpireDate` < '$ExpiresFromToday' AND `ExpireDate` > '$Today') ORDER BY `StartDate` ASC")){
while($row = mysqli_fetch_array($result)){
//show records
}
mysqli_close($mysqli);
}
EDIT
to work with DATEDIFF tell mysql to treat the datetime string as a date:
$Today = date("Y-m-d h:i:s");
if ($result = $mysqli->query("SELECT * FROM `table` WHERE (DATEDIFF(DATE(`ExpireDate`), DATE('$Today')) < 30 AND `ExpireDate` >= '$Today') ORDER BY `StartDate` ASC")){
while($row = mysqli_fetch_array($result)){
//show records
}
mysqli_close($mysqli);
}
Database:
pub_id pub_name time ip
1 King 1359500087 3388636152
2 Queen 1359550082 6385394932
3 Jack 1359502084 5648646562
4 Heart 1359524083 9283834142
5 Jim 1359503082 3388636152
|_ Using time() |_ Using ip2long()
PHP/MySQLi Code:
$pub_id = $_GET['pub_id'];
$pub_name = $_GET['pub_name'];
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$time = time();
$query = $db->query("SELECT * FROM impressions WHERE pub_id = '$pub_id' AND pub_name = '$pub_name' AND ip = '$ip' AND time >= '???'");
$ip_adderss = $query->num_rows;
$query->close();
if($ip_adderss == 0){
// Redirect
} else{
// Do nothing
}
Now using the time() and IP how can i check that the current visitor last visit was 24 hour ago or not?
A simple solution is using if statement to check the ip time and now time.
// Check if the IP is new or returning
$query = $db->query("SELECT * FROM impressions WHERE pub_id = '$pub_id' AND pub_tag = '$pub_tag' AND month = '$month' AND day = '$day' AND ip = '$ip' AND domain = '$domain' AND valid = '1' ORDER BY id DESC");
$ip_address = $query->num_rows;
if($ip_address == 0){
$ip_ok = 1;
} elseif($ip_address != 0){
$impression = $query->fetch_assoc();
if($time >= ($impression['time'] + 86400)){
$ip_ok = 1;
} else{
$ip_ok = 0;
}
} else{
$ip_ok = 0;
}
Your time field contains unix timestamp, which is just a number of seconds.
So, it's easy to calculate a point that lies a day ago - just subtract 86400 from the current timestamp.
So, your condition is going to be as simple as an elementary school math:
WHERE time >= unix_timestamp() - 86400
or, if you want it using time() PHP function
$time = time() - 86400;
$query = "SELECT * FROM impressions WHERE ... AND time >= ?");
and then bind that value.