Adding 2 days and comparing - php

I've written some code to check if 2 days have passed using 2 dates, but it does not seem to work.
<?php
date_default_timezone_set('Europe/Amsterdam');
$_connection = mysqli_connect("localhost", "root", "root", "theater") or die("Error: " . mysqli_error());
$query = "SELECT * FROM Reservering";
$result = mysqli_query($_connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$res = strtotime($row['ReserveringsDatum']);
echo date('d-m-y', $res);
}
mysqli_close($_connection);
?>
$row['ReserveringsDatum'] is a date which looks like this: "07-01-14" (example).
For some reason the echo date('d-m-y', $res); shows me "14-01-07", which is just the day and year being reversed.
Edit:
For those wondering how it ended up, here is the working code:
<?php
date_default_timezone_set('Europe/Amsterdam');
$_connection = mysqli_connect("localhost", "root", "root", "theater") or die("Error: " . mysqli_error());
$query = "SELECT *, DATEDIFF(NOW(), DATE(ReserveringsDatum)) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2 ";
$result = mysqli_query($_connection, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['Betaalt'] == 'nee') {
$query2 = "DELETE FROM Reservering WHERE `ReserveringID` = '".$row['ReserveringID']."'";
mysqli_query($_connection, $query2);
}
}
mysqli_close($_connection);
?>

As said in the comment, i would make the selection within SQL. There is not need selecting all the rows and filter them in PHP. Its something better done in SQL.
Simple Example:
SELECT *, DATEDIFF(NOW(), ReserveringsDatum) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2
Make sure reserveringsdatum is a DATE, if its a TIMESTAMP you need to convert it to DATE.
SELECT *, DATEDIFF(NOW(), DATE(ReserveringsDatum)) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2

Try this
$res = strtotime($row['ReserveringsID']);
$limit = strtotime($row['ReserveringsID']) + strtotime("+2 day", $res);
var_dump($res); var_dump($limit);
if($limit > $res) {
echo "2 days have passed";
} else {
echo "2 days have not yet passed";
}

I think you need to fix you're condition.
If you want to check if $res is more than two days you have to compare limit to the current time, instead of $res.
$res = strtotime($row['ReserveringsID']);
$limit = strtotime('+2 days', $res);
if($limit < time()) {
echo "2 days have passed";
} else {
echo "2 days have not yet passed";
}

Your problem is in this line
$limit = strtotime($row['ReserveringsID']) + $2days;
You need to add 2 days like this one
$res = strtotime($row['ReserveringsID']);
$limit = strtotime('+2 days', $res);
Working demo of adding 2 days to a date
https://eval.in/86632
How do I add 24 hours to a unix timestamp in php?
Adding days to a timestamp

Related

Php sum data between interval date

I have a working code that filters data from the date range.
MY WORKING CODE
<?php
//connection
$conn = new mysqli('xxxx', 'xxxx','xxxx', 'xxxx');
$start = date('Y-m-d', strtotime($_POST['date_start']));
$end = date('Y-m-d', strtotime($_POST['date_end']));
$output = array('error' => false, 'data' => '');
$sql = "SELECT * FROM users WHERE cosafai='polizza' and datapratica BETWEEN '$start' AND '$end'";
$query = $conn->query($sql);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$output['data'] .= "
<tr>
<td>".$row['name']."</td>
<td>".$row['cognome']."</td>
<td>".$row['targa']."</td>
<td>".$row['compagniascelta']."</td>
<td>".$row['premiopolizza']."</td>
<td>".date('M d, Y', strtotime($row['datapratica']))."</td>
</tr>
";
}
}
else{
$output['error'] = true;
}
echo json_encode($output);
?>
now I need to sum a specific column ( Premio polizza )during the dates interval
thinking something like
$sql = "SELECT SUM(premiopolizza) as sum FROM users WHERE cosafai='polizza' and datapratica BETWEEN '$start' AND '$end'";
but honestly, I can't manage it ;)
my final result should be
final result
Since you 're looping over the database result anyway, you can sum up in your while loop.
$sum = 0;
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$sum += $row['premiopolizza'];
$output['data'] .= "
...
";
}
}
The variable $sum is the addition of all $row['premiopolizza'] at the end. There is no need for an additional sql statement in my eyes. At the end you can use the sum in your output like ...
$output['sum_premiopolizza'] = $sum;

how to find the particular date data or next date data in mysql database?

I am trying to find the particular date data from database,
my concept is if 2018-11-30 is given to find in database if the date is present in database it should display the date in output, if not present it should add +1 date to 2018-11-30 and try to find the next date 2018-12-01 like wise it goes on.
but i am facing the problem the date is not checked in the database.i am not sure weather my code is correct or wrong can any one give me solution for it.
this is my code
$Firstdate = '2018-11-29';
$Lastdate = '2018-12-03';
$Sql2 = "SELECT ScheduleDate FROM `empdet`";
$result2 = mysqli_query($con, $Sql2);
while($row = mysqli_fetch_array($result2))
{
if($row["ScheduleDate"]==$Firstdate)
{
$DBfirstdate==$Firstdate;
echo "$DBfirstdatebb",$DBfirstdate;
break;
}
else {
$checkFDBdate=date('Y-m-d', strtotime("+1 day", strtotime($Firstdate)));
if($row["ScheduleDate"]==$checkFDBdate)
{
$DBfirstdate=$checkFDBdate;
echo "$DBfirstdate",$DBfirstdate;
break;
}
}
}
$Sql3 = "SELECT ScheduleDate FROM `empdet`";
$result3 = mysqli_query($con, $Sql3);
while($row = mysqli_fetch_array($result3))
{
if($row["ScheduleDate"] == $Lastdate) {
$DBlastdate==$Lastdate;
echo "$DBlastdateBB",$DBlastdate;
break;
}
else {
$checkLDBdate=date('Y-m-d', strtotime("-1 day", strtotime($Lastdate)));
if($row["ScheduleDate"]==$checkLDBdate)
{
$DBlastdate=$checkLDBdate;
echo "$DBlastdate",$DBlastdate;
break;
}
}
}
$sql ="select * from empdet where ScheduleDate between '".$DBfirstdate."' and '".$DBlastdate."'";
$result = $con->query($sql);
SELECT ScheduleDate FROM `empdet` where ScheduleDate > '$Firstdate' and ScheduleDate < '$Lastdate' order by ScheduleDate limit 1
Try this way. You will get the first raw from the date range given.
Select stuff from somewhere where something > 'value' order by something limit 1

PHP Check if 10 minutes has gone by

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.

SELECT statement not working in mariadb 10.0 but works in mariadb 5.5

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

Storing MySQL Field Datetime in PHP Variable and Adding 1 Hour To It

Using MySQLi and PHP I have a Query Like below and I need to store the orderdate field from MySQL newOrder table (with format of Datetime like 2014-06-15 22:12:00) into a PHP variable like $orderTime and then add 1 Hour to the Time.
<?PHP
include 'conconfig.php';
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$query = "select * from newOrder WHERE orderdate < NOW() ORDER BY id DESC LIMIT 1";
if ($result = $con->query($query))
{
if ($result->num_rows > 0)
{}
else
{
$resultStr = 'Nothing found';
}}
}
$con->close();
is it possible something like inside the while loop?
$orderTime = $row['orderdate'];
$orderTime = $orderTime +1hour;
Thanks
Easily done with date() and strtotime():
$orderTime = date('Y-m-d H:i:s', strtotime($row['orderdate'] . '+ 1 hour'));
Update to answer question in comment:
To check if difference between $ordertime and current time is greater than 2 hours:
if (time() - strtotime($orderTime) > 7200) {
echo 'Difference is greater than 2 hours';
}

Categories