PHP show date2 if date1 passed - php

I need help on this..
I am new in php and dummy..
$displaydate = "";
$paydate1 = "23-10-2016";
$paydate2 = "23-11-2016";
$paydate3 = "23-12-2016";
$paydate4 = "23-01-2017";
$paydate5 = "23-02-2017";
$paydate6 = "23-03-2017";
if todaydate is 23-10-2016 then $displaydate = "$paydate2" until 22-11-2016. When 23-11-2016 then $displaydate = "$paydate3" and so on.
then results
if the date is 23-10-2016 until 22-11-2016 $displaydate = "$paydate2"
if the date is 23-11-2016 until 22-12-2016 $displaydate = "$paydate3"
if the date is 23-12-2016 until 22-01-2016 $displaydate = "$paydate4"
if the date is 23-01-2016 until 22-02-2016 $displaydate = "$paydate5"
if the date is 23-02-2016 until 22-03-2016 $displaydate = "$paydate6"
please help with the code...
Thanks..
IM php DUMMY

Organize your data convenient so you can easy access it.
Put your paydates it an array:
$paydate = ["23-10-2016","23-11-2016","23-12-2016","23-01-2017","23-02-2017","23-03-2017"];
UPDATED per your comment:
$payout1 = $this->data->paymentdate1;
$payout2 = $this->data->paymentdate2;
$payout3 = $this->data->paymentdate3;
$payout4 = $this->data->paymentdate4;
$payout5 = $this->data->paymentdate5;
$payout6 = $this->data->paymentdate6;
$paydate = [$payout1,$payout2,$payout3,$payout4,$payout5,$pa‌​yout6];
Transform the dates in an easy to sort format:
function trf_date($date)
{
return date('Y-m-d', strtotime($date));
}
$paydate = array_map("trf_date", $paydate );
Sort the array to be sure we will get the dates in ascending order while looping.
sort($paydate);
Now loop through the array to find the first date higher then today:
foreach($paydate as $key=>$val){
if($val > date('Y-m-d'))
break;
}
$displaydate = ''; //initialize the output variable
//check to see if the last retrieved date meets the condition not to be in the past.
//this is for the case all dates in the array are in the past
if(isset($paydate[$key]) && $paydate[$key] > date('Y-m-d'))
$displaydate = $paydate[$key];

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

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";
}

How to get the nearest date match in PHP from a SQL Database

I am currently trying to get the nearest match of 2 sets of dates (d-m-Y) against a SQL database and then out put the matched InterestRate column name.
I have an example of my current code, this is mostly pseudo code and trying a few things out. If that helps.
//$XSS_BLOCK2 = "05-05-2016";
$XSS_BLOCK3 = "20-05-2016"; //By the way The '2016-05-20' is user input so it will not be '2016-05-20' all the time, so it could be anything '2014-08-15'.
$today = date('d-m-Y');
$interest = 0;
$securesqlstring = $secureconn->prepare("SELECT * FROM LatePaymentRates");
$securesqlstring->execute();
while($row=$securesqlstring->fetch())
{
echo $row['StartDate'];
echo $row['EndDate'];
echo $row['InterestRate'];
$varsin = array($XSS_BLOCK3, $today);
$DateRange = new DateTime($varsin);
$databasein = array($row['StartDate'], $row['EndDate']);
$DateRanges = new DateTime($databasein);
if(($DateRange >= $DateRanges) && ($DateRange >= $DateRanges)) {
$dayrate = $row['InterestRate'] * $XSS_BLOCK3 / 36500;
$start_date = new DateTime($DateRange);
$end_date = new DateTime($DateRanges);
$dd = date_diff($end_date, $start_date) * $dayrate;
$interest += $dayrate;
}
}
$LatePaymentInterest = $interest;
if (!$securesqlstring) // If there is an error it will show this message.
{exit("Error in the SQL");}
Do we really need to spell this one out? I feel like I must be missing something...
SELECT * FROM my_table WHERE '2016-05-20' BETWEEN startdate AND enddate;

Show text if date is today

I need to show (today) text if date is today. How do I do that!
I tried everything but cant find the right anwser that's why Im asking here.
Here is the piece of codeI have right now.
$mod_list.= '<ul class="upcoming-events"><li>
<div class="date">
<span><span class="day">'.date($dateformat,$datetime_start).'</span>
<span><span class="month">'.date($datemonth,$datetime_start).'</span>
<span><span class="year">'.date($dateyear,$datetime_start).'</span>
</div>';
I want to show it just behind the last </span>
It is for event calendar and I want to show the text TODAY on the exact day of the event.
Any Ideas?
if(date('Y-m-d',$datetime_start)==date('Y-m-d')){
//it's today! put code here
}else{
//it's not today
}
If you don't use the second parameter in the date() function, it uses the current time. So comparing their date to today is that simple.
Ok, here is the whole Code for what I'm using, it is actualy a droplet for showing the event calendar in my sidebar.
//:Show next #N events
//:
// Get_Concerts
global $database, $wb;
setlocale (LC_ALL, 'sl_SI.UTF-8'); //za vse kategorije
setlocale (LC_TIME, 'sl_SI.UTF-8'); //za datumske funkcije
// Show how many items, defaults to 10?
if ( !isset($max) ){ $max = 10; };
// year and month and section defaults
if(!isset($year)) {$year = date('Y', time()); }
if(!isset($month)) {$month = date('n', time()); }
if(!isset($section_id)) {$section_id = 0 ; }
// Set dateformat to suit your needs, add timeformat if needed
$dateformat = 'd'; // Standard php date formats
$datemonth = 'M'; // Standard php date formats
$dateyear = 'Y'; // Standard php date formats
// Fetch base page link, if event_id = set
$extrasql = '';
$page_id = 0;
$page_link ='';
if ($section_id<>0) {
$extrasql = " section_id = '".$section_id."' AND ";
$sql = "SELECT page_id FROM ".TABLE_PREFIX."sections WHERE section_id = '".$section_id."'";
$result = $database->query($sql);
if ( $result->numRows() > 0 ) {
while( $row = $result->fetchRow() ) {
$page_id = $row['page_id'];
}
}
if ($page_id <> 0) {
$sql = "SELECT link FROM ".TABLE_PREFIX."pages WHERE page_id = '".$page_id."'";
$result = $database->query($sql);
if ( $result->numRows() > 0 ) {
while( $row = $result->fetchRow() ) {
$page_link = page_link($row['link']);
}
}
}
}
// Set start- and end date for query
// $datestart = "$year-$month-1"; ORIGINAL = show all events in this month
$datestart = date("Y-m-d"); // ALTERNATIVE = show all events in this month, starting today
$dateend = "$year-$month-".cal_days_in_month(CAL_GREGORIAN, $month,$year);
$mod_list = "";
// Fetch the items
$sql = "SELECT DAY(date_start) AS day, id, custom1, date_start, time_start, date_end, time_end, name FROM ".TABLE_PREFIX."mod_procalendar_actions WHERE ".$extrasql." date_start >='$datestart' AND public_stat = 0 ORDER BY date_start,time_start LIMIT 0, ".$max." ";
$mod_query = $database->query($sql);
while ( $row =& $mod_query->fetchRow()){
// Build url like : pages/kalendar.php?id=2&detail=1
$page_url = $page_link.'?id='.$row['id'].'&detail=1';
$ds = $row['date_start']." ".substr($row['time_start'],0,5);
$de = $row['date_end']." ".substr($row['time_end'],0,5);
$datetime_start = mktime(substr($ds,11,2),substr($ds,14,2),0,substr($ds,5,2),substr($ds,8,2),substr($ds,0,4));
$datetime_end = mktime(substr($de,11,2),substr($de,14,2),0,substr($de,5,2),substr($de,8,2),substr($de,0,4));
if ($row['time_start'] !== $printTime) {
$printTime = $row['time_start'];
$mod_list.= '<ul class="upcoming-events"><li>
<div class="date"><span><span class="day">'.date($dateformat,$datetime_start).'</span><span><span class="month">'.date($datemonth,$datetime_start).'</span><span><span class="year">'.date($dateyear,$datetime_start).'</span>
</div>';
$mod_list.= '<div class="event-content"><h6>'.$row["name"].'</h6>
<ul class="event-meta"><li><i class="fa fa-clock-o"> </i>'.substr($printTime,0,5).'<sup>h</sup></li>
<!-- <li><i class="fa fa-info-circle"> </i>'.$row["custom1"].'</li> --></ul></div></li></ul>';
}
$mod_list .= "<hr>";
}
$mod_list .= 'Napovednik<br></br>';
return $mod_list;
Here is the link to the site, LINK you'll notice a TEST event which is created for today, I want a little TODAY text to be shown right beside the HOUR on the right.
I hope this helps more, Thank you
R.

convert MySQL date result to monthname and create variables

I have a MySQL database with a date column.
I create a variable of the value in PHP like this:
$query = mysql_query ("SELECT customer_date FROM customers WHERE customer_id = {$_SESSION['session_id']}");
while ($result = mysql_fetch_object($query)) {
$date = $result->customer_date;
}
I need to convert the $datefrom YYYY-MM-DD to three variables
$yearvalue (for example 2012)
$monthname (for example August)
$dayvalue (for example 10)
And I need to be able to echo out anywhere in my code... How would I do this in a fancy way? I'm pretty new to coding...
Here:
while ($result = mysql_fetch_object($query)) {
$date = $result->customer_date;
$yearvalue = date("Y", strtotime($date) );
$monthname = date("F", strtotime($date) );
$dayvalue = date("d", strtotime($date) );
}
It'll only work/store the value of these values for the last row outputted from the $result.
how about this?
while ($result = mysql_fetch_object($query)) {
$date = $result->customer_date;
list($year,$month,$day,$hour,$minute,$second)=
explode('-',date('Y-F-d-h-i-s',strtotime($date)));
}
Also read this. You will need to play with Y-F-d-h-i-s as per your requirement.

Categories