comparing date and time php - php

i need to compare two dates where if one date is greater than the other then an sql will run. this is my code
date_default_timezone_set('Asia/Kuala_Lumpur');
$date = date('Y-m-d G:i:s');
$query = mysql_query("SELECT * FROM package_transaction");
if(mysql_num_rows($query) > 0) {
while($row = mysql_fetch_array($query)) {
$transac_code = $row['transac_code'];
$duedate = $row['payment_due'];
if(strtotime($date) > strtotime($duedate))
{
mysql_query("UPDATE package_transaction SET `status` = 'cancelled' WHERE `payment_due` = `$duedate` AND `transac_code` = `$transac_code`");
}
}
}
but its not working. please help

try this,
date("Y-m-d", strtotime($date)) > date("Y-m-d", strtotime($duedate))

could you try and use the date format before using strtotime
$duedate = $row['payment_due'];
$duedate = $duedate->format('Y-m-d G:i:s');

Related

Inputting/overwriting information in arrays with PHP

I have a small PHP page which takes data from MySQL and displays it via PHP in a monthly calendar. I'm having trouble arranging the data properly within an array to get the desired output.
First, I will describe what I would like to happen:
students come to classes on regular days of the week
they can also make or cancel reservations
the calendar also displays days when the school is not open
In order to display this data on the calendar, I use MySQL to output data from a variety of sources, and then input that into an array with PHP, which I sort by date and output.
My issue is, I would like to be able to handle more than one row of data per day, but because I am using the date as the key, I am limited on only displaying one result per day. If I use a loop to append the date with a counter in the key, I get overlapping results in situations where someone made a reservation and then cancelled that reservation on the same day.
As for my code...
First, I check to see if the student is registered in a weekly class, then input that class into the array.
$sql = "SELECT StudentDB.studentid, ClassDB.classID, ClassDB.class_level, ClassDB.class_title, ClassDB.time, ClassDB.teacher, StudentDB.first_name, StudentDB.last_name, StudentDB.payment_amount, ClassDB.day
FROM ClassDB
INNER JOIN RegDB ON ClassDB.classID = RegDB.classid
INNER JOIN StudentDB ON StudentDB.studentID = RegDB.studentid
WHERE StudentDB.studentid = '$studentid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { // DISPLAY REGULAR CLASS DATA
$dayofclass = $row['day'];
$class_level = $row['class_level'];
$class_title = $row["class_title"];
$day = $row["day"];
$class_time = $row["class_time"];
$time = $row["time"];
// check which dates match the days of the week and store in an array
for ($i=1;$i<=$n;$i++){
if ($i<10) {
$i = "0" . $i;
}
$day=date("l",strtotime($yearmonth.$i)); //find weekdays
if($day==$dayofclass){
$time = date("H:i",strtotime($row['time']));
$dates[]=$yearmonth.$i;
$datesdata[$yearmonth.$i] = "0";
$timedata[$yearmonth.$i] = $time;
$classiddate[$yearmonth.$i] = $row['classID'];
}
}
}
echo "</table>";
$conn->close();
}
After that, I check for specific reservations (cancelations, irregular reservations, waitlists) and input them into the array:
$lowerlimit = $yearmonth . "01";
$upperlimit = $yearmonth . "31";
$sql = "SELECT AttendanceDB.*, ClassDB.*
FROM StudentDB
INNER JOIN AttendanceDB ON StudentDB.studentid = AttendanceDB.studentid
INNER JOIN ClassDB ON AttendanceDB.classid = ClassDB.classID
WHERE StudentDB.studentid = '$studentid'
AND AttendanceDB.class_time >= '$lowerlimit'
AND AttendanceDB.class_time <= '$upperlimit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$loopcount = 0;
// store furikae data in the array
while($row = $result->fetch_assoc()) {
$phpdate = strtotime( $row["class_time"] );
$time = date("H:i",strtotime($row['time']));
$mysqldate = date( 'Y-m-d', $phpdate );
$loopcount++;
$mysqldate = $mysqldate . "+" . $loopcount;
// $loopcount++;
// $mysqldate = $mysqldate . "+" . $loopcount;
$previousdate = $mysqldate;
$previousfurikae = $row['furikae'];
if ($row["furikae"] == 3){
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "1";
$timedata[$mysqldate] = $time;
$classiddate[$mysqldate] = $row['classID'];
} elseif ($row["furikae"] == 8 OR $row["furikae"] == 7) {
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "3";
$timedata[$mysqldate] = $time;
} elseif ($row["furikae"] == 2) {
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "2";
$timedata[$mysqldate] = $time;
}
}
}
$conn->close();
Then finally I check the school calendar and input the days off into the array:
$sql = "SELECT *
FROM SchoolScheduleDB
WHERE date >= '$lowerlimit'
AND date <= '$upperlimit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// store furikae data in the array
while($row = $result->fetch_assoc()) {
$phpdate = strtotime( $row["date"] );
// $time = date("H:i",strtotime($row['time']));
// $mysqldate = date( 'Y-m-d', $phpdate ) . " " . $time;
$mysqldate = date( 'Y-m-d', $phpdate );
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "666";
}
}
$conn->close();
The way I intended it to work was that:
First the regular classes would be input
Then any reservations would overwrite the original plans
And finally the school calendar would overwrite everything
Currently, this functions as it should, but it is limited to displaying 1 result per day, but I would like to be able to display more than 1 result per day for students who come to multiple classes.
Thank you for your help. If I made any mistakes in my question or my question is unclear I will do my best to revise it.
You can make a Sub-Array for each date by using edged brackets:
$data[20180528][] = 'aa';
$data[20180528][] = 'bb';
$data[20180529][] = 'cc';
$data[20180529][] = 'dd';
$data[20180529][] = 'ee';
will give you an Array like this:
20180528 => aa
=> bb
20180529 => cc
=> dd
=> ee

MySQL: How do I search by timestamp but convert timezone first?

I need to be able to get the total amount spent either monthly or daily. To do that I do sum(tblaccounts.amountin) but the issue i'm having is I need to convert my date column to a different timezone fist. I've tried messing with convert_tz(date,"+00:00","+10:00") but not sure how to use it with LIKE.
How can I get records for monthly or daily based on the $period variable while first converting the timestamp?
Something like WHERE convert_tz(date) LIKE $date_to_check%
function check_limit($period='monthlylimit') {
if ($period == 'monthlylimit') {
$date_to_check = date("Y-m");
}
else { ### Day period
$date_to_check = date("Y-m-d");
}
$select = "SELECT
sum(tblaccounts.amountin) as amountin
FROM tblaccounts
WHERE date LIKE '" . $date_to_check . "%'";
}
Utilizing the timezone change inside mysql, this should work out:
if ($period == 'monthlylimit') {
$date = date('Ym');
$format = '%Y%m';
} else {
$date = date('Ymd');
$format = '%Y%m%d';
}
$sql = "SELECT SUM(t.amountin) as amountin FROM tblaccounts t WHERE
DATE_FORMAT(CONVERT_TZ(t.date,'+00:00','+10:00'),'". $format ."') = '". $date ."'";
The correct timezone numbers, will depend on what you have mysql defaulted too, and your desired result. You may have to twiddle with that number.
Or you can change the timezone for the date on php's side and skip mysql tz converting:
$dt = new DateTime("now", new DateTimeZone($tz));// $tz to equal what you are aiming for
$dt->setTimestamp(time());// might not be needed
if ($period == 'monthlylimit') {
$date = $dt->format('Ym');
$format = '%Y%m';
} else {
$date = $dt->format('Ymd');
$format = '%Y%m%d';
}
$sql = "SELECT SUM(t.amountin) as amountin FROM tblaccounts t WHERE
DATE_FORMAT(t.date,'". $format ."') = '". $date ."'";
Note: I did not use LIKE here, as that is why I introduced DATE_FORMAT to set it to a single value to compare on.

How do I calculate one's retirement date?

I'm trying to use one's date of birth to calculate when he'll be 50, if he's not 50 already.
If person is not 50, add a year to his age then check if it'll be 50. If not, iterate until it's true. Then get the date he turned 50. in PHP
Here's the code, not complete.
$rAge = 50;
$retir = date('j F Y ', strtotime("+30 days"));
$oneMonthAdded = strtotime(date("d-m-Y", strtotime($DOB)). "+1 year");
$re = date("d-m-Y", $oneMonthAdded);
$futDate = date("d-m-Y", strtotime(date("d-m-Y", strtotime($re))));
$date_diff = strtotime($futDate)-strtotime($DOB);
$future_age = floor(($date_diff)/(60*60*24*365));
Help please.
try this code bro!
// your date of birth
$dateOfBirth = '1950-11-26';
// date when he'll turn 50
$dateToFifty = date('Y-m-d', strtotime($dateOfBirth . '+50 Years'));
// current date
$currentDate = date('Y-m-d');
$result = 'retired';
// checks if already fifty
if($currentDate <= $dateToFifty) {
$result = $dateToFifty;
}
echo $result;
I use simplest php code to find out retire date. y
<?php
$dob = '1970-02-01';
$dob_ex = explode("-",$dob);
$age_diff = date_diff(date_create($dob), date_create('today'))->y;
$year_of_retire = 50 - $age_diff;
$end = date('Y', strtotime('+'.$year_of_retire.'years'));
$date_of_retire = $end."-".$dob_ex[1]."-".$dob_ex[2];
echo $date_of_retire;
?>
you can use if...else condition to echo values according to you.
like
if($year_of_retire > 0){
echo $date_of_retire;
} else if($year_of_retire < 0){
echo "retired";
}

Add value (Array) in database

I tried this code but it does not work for me. i just want to add the array value to database. it give me error like this
Notice: Undefined offset: 2
Here is my code:
$timeadd = date("m-d-Y H:i:s", strtotime('+6 hours'));
$extinvoice=mysqli_query($link,"Select * from invoice WHERE BRANCH_CODE_MX='".$display_branchcode."' and INVOICE_NO_MX='".$invoicecode."' and INVOICE_ITEM_UNIT_MX='EXTENDEDWARRANTY'");
while($extrow=mysqli_fetch_array($extinvoice))
{
$ewtitemcode=$extrow["INVOICE_ITEM_CODE_MX"];
$imeiserialunit=$extrow["EWT_IMEI_MX"];
$customercode=$extrow["INVOICE_CUS_CODE_MX"];
$ewtarray[] = "('$invoicecode','$ewtitemcode', '$imeiserialunit','$customercode','$display_branchcode','$timeadd')";
}
$arrayitem=count($ewtarray);
for($item = 0; $item <= $arrayitem; $item++)
{
$sql = mysqli_query($link,"INSERT INTO extended_warranty
(INVOICE_NO_MX,FORM_EW_MX,EW_SERIAL_MX,CUSTOMER_CODE,BRANCH_CODE_MX,DATE_ADDED)
VALUES
($ewtarray[$item])");
}
The database requires a datatime in the format
2016-10-02 10:00:00
So change this
$timeadd = date("m-d-Y H:i:s", strtotime('+6 hours'));
to
$timeadd = date("Y-m-d H:i:s", strtotime('+6 hours'));
Additionally to the other users I have removed the double brackets. What happens now?
$timeadd = date("Y-m-d H:i:s", strtotime('+6 hours'));
$extinvoice=mysqli_query($link,"Select * from invoice WHERE BRANCH_CODE_MX='".$display_branchcode."' and INVOICE_NO_MX='".$invoicecode."' and INVOICE_ITEM_UNIT_MX='EXTENDEDWARRANTY'");
while ($extrow=mysqli_fetch_array($extinvoice)) {
$ewtitemcode=$extrow["INVOICE_ITEM_CODE_MX"];
$imeiserialunit=$extrow["EWT_IMEI_MX"];
$customercode=$extrow["INVOICE_CUS_CODE_MX"];
$ewtarray[] = "('$invoicecode','$ewtitemcode', '$imeiserialunit','$customercode','$display_branchcode','$timeadd')";
}
for ($item = 0; $item < count($ewtarray); $item++) {
$sql = mysqli_query($link,"INSERT INTO extended_warranty
(INVOICE_NO_MX,FORM_EW_MX,EW_SERIAL_MX,CUSTOMER_CODE,BRANCH_CODE_MX,DATE_ADDED)
VALUES
$ewtarray[$item]");
}

Automatically inactivate after a certain date

I want to make an advertisment manager. When an ad reaches its expiry date it becomes non-active. But when I tried to make it and tried it, all of the ads change into non-active even though they haven't reached their expiry dates.
Here's my code:
$query_banner = mysql_query("SELECT * FROM ad_tbl ORDER BY ID DESC LIMIT $from,$max_show") or die(mysql_error());
while($show=mysql_fetch_array($query_banner))
{
$no++;
if(($no%2)==0)
$color = '#f2f2f2';
else
$color = '#f9f9f9';
$expired_date = $show['expiry_date'];
$today_date = date("m/d/Y");
$expired = strtotime($expiry_date);
$today = strtotime($today_date);
if($expired > $today)
{
$valid = "yes";
}
else
{
$valid = "no";
$query_expired = mysql_query("UPDATE ad_tbl SET status='Non-Active' WHERE expiry_date <= $today") or die(mysql_error());
}
}
Try:
$expiredDateTime = new DateTime($expiry_date);
$expired = $expiredDateTime->format('U');
$today = date('U'); // This will default give you timestamp for "now", saving you a step
If that works then I fear your m/d/y format could be the root of the issue. To check you should echo your strtotime values out and stick them into a converter, see what it says.

Categories