PHP Print Date data from database for each date - php

I have a database called Holidays which has a date field to save holiday date called STARTTIME, and a duration field to save how many days is the holiday called DURATION. I want to collect all data from that table between some month and year, and print the date 1 by 1.
For Example, here's my data at database:
STARTTIME | DURATION
2016-12-09 | 1
2016-12-15 | 5
How to print it in php 1 by 1 per date? So it will result:
2016-12-09
2016-12-15
2016-12-16
2016-12-17
2016-12-18
2016-12-19
2016-12-20
My code now is like this:
//startDate and endDate is get from my filter, this is only for example
$startDate = '2016-01-01';
$endDate = '2016-01-31';
$sqlHol = "SELECT STARTTIME, DURATION FROM HOLIDAYS WHERE DATEVALUE(STARTTIME) BETWEEN DateAdd('m',-1,#$startDate#) AND #$endDate#";
$queryHol = $db->query($sqlHol);
$hols = $queryHol->fetchAll();
echo '<br />';
//testing to print out array result
print_r($hols);
//looping through data from database
foreach($hols as $hol)
{
for($i=1; $i <= $hol[1]; $i++)
{
echo '<br />';
$due = date_create($hol[0]);
echo date_format($due, 'Y-m-d');
$due = date_add(date_create($hol[0]), date_interval_create_from_date_string('1 days'));
echo '<br />';
}
}
And here's my result (the date doesn't increment):
2015-12-09
2015-12-15
2015-12-15
2015-12-15
2015-12-15
2015-12-15
2015-12-15
Anyone know how to create an output like I need?

It looks like you are writing the due date before you increment it. Try using the loop counter as a way to keep track of how many times you have incremented the date.
foreach($hols as $hol)
{
for($i=0; $i <= $hol[1]-1; $i++)
{
echo '<br />';
$due = date_create($hol[0]);
$due = date_add(date_create($hol[0]), date_interval_create_from_date_string(i.' days'));
echo date_format($due, 'Y-m-d');
echo '<br />';
}
}

Related

php maintain date increments in months, weeks, days from past date to present date

I'm struggling to formulate this question correctly.
I have a php time() entry in a mysql table column called renew. I have a second entry in the same row under the column type which decides when to update the row, namely: daily or weekly or monthly from the renew column value (date).
How this script works:
In this example on row id 1; the balance must be updated to reflect the budget monthly. The renew date must also be updated to reflect the next monthly incremented date after the update has taken place.
in row id 2; This will take place weekly. and so on.
for example:
| id | renew | type | budget | balance |
|----| ---------- | ---------| ------ | ------- |
| 1 | 1611214417 | monthly | 10,000.00 | 3,000.00 |
| 2 | 1643614417 | weekly | 4,000.00 | 600,00 |
id 1 = 2021-01-21 07:33:37;
id 2 = 2022-01-31 07:33:37;
in row id 1 how to get the next update date from today?
//the time entry
$now = time():
$today = 28/02/2022
$updatetime = $table['renew'];
$updatetype = $table['type'];
How i did the weekly:
from the $updatetime variable above, I incremented the variable with one week until it just passes the $now time.
// what I've done for weekly and seems to be working
for($i = 0; $i < 1000000000; $i++ ){ //random high number for incrementing
if($updatetime < $now){
$updatetime = $updatetime + (86400 * 7); //add one week
} else {
return;
}
}
// the next update will now be the new $updatetime for weekly
How can i do this for the monthly? there are no fixed days in a month, the renew date could fall on the 31 of the month or 29 of February and then the current month could only have 30 days or 28 days.
This is where my issue lies.
If you can assist me.
I would recommend to use PHP DateTime object that is much simpler to manipulate the date time using relative formats
<?php
$today = new DateTime();
$updatetime = '19/01/2021'; // $table['renew']; //19/01/2021
$updatetype = 'weekly'; //$table['type']; //daily || weekly || monthly
$updatetime = (new DateTime())->createFromFormat('d/m/Y', updatetime);
// what I've done for weekly and seems to be working
if($updatetime < $today){
// $updatetime = $today; // reset to today if needed
$updatetime->modify('next week'); // add one week
} else {
return;
}
echo 'Next time of weekly update '. $updatetime->format('Y-m-d') . PHP_EOL . PHP_EOL;
// Output: Next time of weekly update 2022-03-07
// without time reset: Next time of weekly update 2021-01-25
Other examples of date manipulation using relative formats:
<?php
$today = '2022-02-28';
$t = new DateTime($today);
// print the source date time
echo $t->format('Y-m-d') . PHP_EOL;
// examples of continuously manipulate the date time origin
echo $t->modify('next week')->format('Y-m-d') . PHP_EOL;
echo $t->modify('next month')->format('Y-m-d') . PHP_EOL;
echo $t->modify('next year')->format('Y-m-d') . PHP_EOL;
echo $t->modify('next sunday')->format('Y-m-d') . PHP_EOL;
/*
Output:
2022-02-28
2022-03-07
2022-04-07
2023-04-07
2023-04-09
*/
Live demo Live demo without time reset
TIP:
Convert your daily, weekly, monthly into infinitive day, week, month so you will be able to use its value directly using $table['type'] into the date time manipulation:
<?php
$updatetype = 'week'; //$table['type']; //day || week || month
$updatetime->modify('next ' . $table['type']); // add one xxx dynamically!
TIP2*
Use ISO date format Y-m-d to simplify your codding.
$updatetime = '2021-01-19'; //'19/01/2021'
$updatetime = new DateTime($updatetime); // That's it!
Thanks to Ino's answers i worked it out like this:
$today = time(); // can use DateTime() too.
$updatetime = '1611214417'; // $table['renew']; //19/01/2021
$updatetype = 'weekly'; //$table['type']; //daily || weekly || monthly
echo $updatetime.'<br>';
for($i = 0; $i < 100000; $i++){
if($updatetime < $today){
$updatetime = strtotime("+1 week", $updatetime); // can add week month day
} else {
break;
}
}
echo $updatetime.'<br>'; // just for comparison
echo date('Y-m-d', $updatetime); // 2022-03-03 works out perfectly

php current weekdays name with date

I want to create a list of weekday dates with name of the weekday.
If today is monday - 2017-01-02 (Y-m-d), then I want the list to be something like this:
Mon-02 | Tue-03 | Wed-04 | Thu-05 | Fri-06 | Sat-07 | Sun-08
My code below will give such result, if today is monday.
This is what I have so far.
function NextDayDate($day) {
return new DateTime('next ' . $day);
}
$dt = new DateTime();
$today=date("l");
if ($today=="Monday") {
echo $dt->format('d'); // Todays date
echo '</br>';
}
elseif ($today!="Monday"){
echo '</br>';
$nextMonday = NextDayDate('Monday');
echo $nextMonday->format('d'); // Next date
echo '</br>';
}
if ($today=="Tuesday") {
echo $dt->format('d'); // Todays date
echo '</br>';
}
elseif ($today!="Tuesday"){
echo '</br>';
$nextMonday = NextDayDate('Tuesday');
echo $nextMonday->format('d'); // Next date
echo '</br>';
}
If today is Tuesday, then for monday I will have Mon-09 because that is the next date for monday.
Mon-09 | Tue-03 | Wed-04 | Thu-05 | Fri-06 | Sat-07 | Sun-08
I want to keep last days date so the list does not change.
Maybe there is a way to get current weeks day names with date?
It is much more easy:
$a = new DateTime();
$oneDay = new DateInterval("P1D");
// Here you add one day to your date until it will Monday
while ($a->format('D') != 'Mon') {
$a->add($oneDay);
}
// Here you print 7 days from your target Monday
for ($i = 0; $i < 7; $i++) {
echo $a->format("D-d");
$a->add($oneDay);
}

looping and date growing 7 days according in php

I want to enter the data with looping and date growing 7 days according total input events
For example, on my form data input like this :
Input Date : 2015-11-27
Input Event : Meeting
Total Event : 3
This is my PHP code to insert with looping :
$date= date("Y-m-d", strtotime($_POST['date']));
$getDate= date('Y-m-d', strtotime($date. ' + 7 days'));
$event = $_POST['event'];
$ttl_event = $_POST['ttl_event'];
for ($i = 0; $i < $ttl_event; $i++) {
$query = mysql_query("INSERT INTO schedule values('','$getDate','$event')")or die(mysql_error());
}
And then finally in table, i want to like this :
id | date | event
1 2015-11-27 Meeting
2 2015-12-04 Metting
3 2015-12-11 Meeting
now, i always error with date always "2015-12-04" :(
please, correct my code.
You need to calculate future dates inside the loop, and increment the addition for each iteration. Meaning you wanna do +0, +7, +14...
for ($i = 0; $i < $ttl_event; $i++) {
$getDate= date('Y-m-d', strtotime($date.' +'.($i*7).'days'));
$query = mysql_query("INSERT INTO schedule values('','$getDate','$event')")
^ are you sure about this ?
or die(mysql_error());
}
Or you can write it like that
$getDate= date('Y-m-d', strtotime('+'.($i*7).'days', $date));
http://php.net/manual/fr/function.strtotime.php

check if date is within a date range

I have a database filled with a bunch of jobs, where I have startDate and endDate.
What Im trying to do is to list current week and 20 weeks ahead, and see if those weeks are within the database.
And when I echo it out I want the date to be green if the date exists and black if not.
It works, but the problem is that it skips the first week. So if I have 2014-07-01 as startDate and 2014-07-14 as endDate, then the second week in that example will get green, not the first one.
This is what I'v done:
UPDATED
$last = 19;
$today = new \DateTime();
$today->modify('Monday this week');
for ($i=0; $i<$last; $i++) {
$the_week = $today->format('o-m-d');
$sql = mysql_query("SELECT startDate,endDate FROM work WHERE '$the_week' BETWEEN startDate AND endDate'");
$row = mysql_fetch_array($sql);
$startdate = $row['startDate'];
$enddate = $row['endDate'];
if(($startdate > $the_week) AND ($enddate < $the_week)) {
$color = "#69dd54;"; } else { $color = "#ffffff;"; }
echo "<span style='color: ". $color ."'>". $the_week ."</span>";
$new_today->modify('next Monday');
}
What is $the_week? It appears to be a date, but there are many dates in a week. For example there is the first date of a week and the last date of the week. It could be that you have a problematic boundary condition here.
You want the start date to be before the last day of a week, and the end date to be after the first day of a week, I am assuming. Therefore the first week gets excluded because its first day is before the start date, and yet its last day is after the start date.
UPDATE:
Consider having:
$the_week = date('o-m-d', strtotime($today. ' + '. $week .' week'));
$the_week_last = date('o-m-d', strtotime($today. ($week +1) .' week'));
By the way, I would recommend you do a single SQL query for this, rather than one for every week. There is an example of how to do that here.
this is the output of your foreach loop for $the_week
2014-07-09
2014-07-16
2014-07-23
2014-07-30
2014-08-06
2014-08-13
2014-08-20
2014-08-27
2014-09-03
2014-09-10
2014-09-17
2014-09-24
2014-10-01
2014-10-08
2014-10-15
2014-10-22
2014-10-29
2014-11-05
2014-11-12
2014-11-19
as you can see the second one is outside of your date range
Try this as your loop
//$first = 0;
$last = 19;
//$weeks = range($first, $last);
$today = new \DateTime();
$today->modify('Monday this week');
for ($i=0; $i<$last; $i++) {
$the_week = $today->format('o-m-d');
$sql = mysql_query("SELECT startDate,endDate FROM work WHERE $the_week BETWEEN startData AND endDate"); //what happend to your original query.
$r = mysql_num_rows($sql);
$row = mysql_fetch_array($sql);
$startdate = $row['startDate'];
$enddate = $row['endDate'];
if(($startdate > $the_week) AND ($enddate < $the_week)) {
$color = "#69dd54;"; } else { $color = "#ffffff;";
}
echo "<span style='color: ". $color ."'>". $the_week ."</span>";
$today->modify('next Monday');
}
outputs
2014-07-07
2014-07-14
2014-07-21
2014-07-28
2014-08-04
2014-08-11
2014-08-18
2014-08-25
2014-09-01
2014-09-08
2014-09-15
2014-09-22
2014-09-29
2014-10-06
2014-10-13
2014-10-20
2014-10-27
2014-11-03
2014-11-10
Using DateTime you can increment by the 'next Monday' or any day for that matter, with a simple for loop.
also make sure to change
$startdate = $ro['startDate'];
$enddate = $ro['endDate'];
to
$startdate = $row['startDate'];
$enddate = $row['endDate'];

Getting appointments for the next 5 days using php

I am trying to write a script to pull dates for the next 7 days and put them into a div for each date :
echo '<div class="dateboxcontainer">';
for($i=0; $i<=6; $i++){
echo '<div class="datebox"><div class="topdate">'.strtoupper(date("D d", mktime(0, 0, 0, 0, date("d")+$i, 0))."\n").
'</div><div class="bottomdate">An appointment for the day</div></div>';
}
echo '</div>';
Im now trying to pull data from my database from two fields 'datedroppingoff' and 'datepickingup', which are formatted like this '2013-07-10 14:29:28'.
Im kind of stuck though as im not sure what query to write to put the appointments for each day into each day div where 'some info' currently sits.
Im guessing it would be something like
Select * FROM jobdetails WHERE datedroppingoff OR datepickingup = WHATEVER DAY IS BEING ECHO'D OUT
but im not quite sure how I can compare the date stored in jobdetails for that row to the date being echo'd out ?.
Edit>>>>>
Thanks for the answers below, iv managed to come up with the following, it echos out the date boxes ok, but doesnt bring in any data, so im not sure if I have the sql part correct ?.
echo '<div class="dateboxcontainer">';
$eventdata = <<<SQL
SELECT *
FROM `jobdetails`
SQL;
if(!$events = $db->query($eventdata)){
die('There was an error running the query [' . $db->error . ']');
}
// read first event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the first one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $datedroppingoff;
} else // no events?
$nextDate = 0; // prepare a fake date value
// calculate today date
$currentDate = mktime();
// loop on the dates for the next 7 days
for ($i = 0 ; $i < 7; $i++) {
$currentEvents = "";
// loop to print every event for current day (first one already extracted)
while ($nextDate == date("Y-m-d", $currentDate)) { // next event occurs today
// here prepare the var containing the event description
// BTW, I'd use a list for the events
$currentEvents .= "· $name<br>"; // use every field you need from current DB row
// read next event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the next one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $datedroppingoff;
} else // no more events?
$nextDate = 0; // prepare a fake date value
}
echo "
<div class='datebox'>
<div class='topdate'>" . strtoupper(date("D d m Y", $currentDate)) . "</div>
<div class='bottomdate'>$currentEvents</div>
</div>";
$currentDate = strtotime("+1 day", $currentDate);
}
echo '</div>';
Can you use something like this:
SELECT * FROM `jobdetails` WHERE (`datedroppingoff ` > '2013-07-01 00:00:00' AND `datedroppingoff ` '2013-07-02 00:00:00') OR (`datepickingup ` > '2013-07-01 00:00:00' AND `datepickingup ` '2013-07-02 00:00:00');
This will have to be repeated per day (i.e. for each of the 5 days)
To do a nice loop, use an array populated with the next 5 dates as strings. Then do a foreach over the dates and run this query.
If you want all dates from now and for the next 5 days, you could use:
WHERE
`datedroppingoff` BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 5 DAY) OR
`datepickingup ` BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 5 DAY)
Let's see how I'd proceed (by the way, this is my first answer, so I'm a little excited...)
First, some basic assumptions for this ultra-fast script (sorry, not so much time now to test it thoroughly).
your Appointment table has a field with the date of the appointment
your result resource ($events) contains only the rows for the current week
the resulting rows are sorted by the date field, ascending (from oldest to newest)
Try this (I've changed a bit your original code, sorry)
// read first event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the first one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $DB_field_with_event_date;
} else // no events?
$nextDate = 0; // prepare a fake date value
// calculate today date
$currentDate = mktime();
// loop on the dates for the next 7 days
for ($i = 0 ; $i < 7; $i++) {
$currentEvents = "";
// loop to print every event for current day (first one already extracted)
while ($nextDate == date("Y-m-d", $currentDate)) { // next event occurs today
// here prepare the var containing the event description
// BTW, I'd use a list for the events
$currentEvents .= "· $your_desc_field<br>"; // use every field you need from current DB row
// read next event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the next one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $DB_field_with_event_date;
} else // no more events?
$nextDate = 0; // prepare a fake date value
}
echo "
<div class='datebox'>
<div class='topdate'>" . strtoupper(date("D d m Y", $currentDate)) . "</div>
<div class='bottomdate'>$currentEvents</div>
</div>";
$currentDate = strtotime("+1 day", $currentDate);
}
Tried a couple of times on fake data and it should work. IMHO better to directly alias the date field to get the nextDate var directly from the DB, so avoiding the rows,
$nextDate = $DB_field_with_event_date;
I used this in the end which seems to do the job ! :)
// Date box container
echo '<div class="dateboxcontainer">';
// Loop through and create a date for the next 7 days
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 7);
foreach ($days as $day) {
echo '<div class="datebox">';
echo '<div class="topdate">';
echo strtoupper($day->format('D d')) . PHP_EOL;
echo '</div>';
// Get the names for each day
$theday = strtoupper($day->format('Y-m-d'));
$sqldate = <<<SQL
SELECT *
FROM `jobdetails`
WHERE datedroppingoff = '$theday' OR datepickingup = '$theday'
SQL;
if(!$resultdate = $db->query($sqldate)){
die('There was an error running the query [' . $db->error . ']');
}
while($rowdate = $resultdate->fetch_assoc()){
echo $rowdate['name'];
}
//
echo '</div>';
}
echo '</div>';
//

Categories