PHP Calendar - Hide Days Previous To Today - php

I have a calendar on my website using PHP/HTML and it works fine except that for some reason it is displaying the last 5 days previous to today's date when ideally I want them to be hidden. Here is my PHP & CSS code:
.calendarHeader{
text-align: center;
text-decoration: underline;
color: #303030;
}
.calendarDates{
margin: 30px auto auto auto;
width: 280px;
}
.calendar{
margin: 10px auto auto auto;
width: 280px;
}
.calendarCell{
float: left;
width: 40px;
color: #707070;
text-align: center;
padding: 5px 0px 5px 0px;
}
.calendarCell:hover{
color: #000000;
}
.calendarBlank{
color: #E9EAEB;
cursor: default;
}
.calendarBlank:hover{
color: #FFFFFF;
}
.calendarToday{
color: #BC3415;
font-weight: bold;
}
<?php
$today = date("d"); // Current day
$month = date("m"); // Current month
$displaymonth = date("F");
$year = date("Y"); // Current year
$days = cal_days_in_month(CAL_GREGORIAN,$month,$year); // Days in current month
$lastmonth = date("t", mktime(0,0,0,$month-1,1,$year)); // Days in previous month
$start = date("N", mktime(0,0,0,$month,1,$year)); // Starting day of current month
$finish = date("N", mktime(0,0,0,$month,$days,$year)); // Finishing day of current month
$laststart = $start - 1; // Days of previous month in calander
$counter = 1;
$nextMonthCounter = 1;
echo '
<div class="calendarHeader"><strong>'.$displaymonth.' '.$year.'</strong></div>
<div class="calendarDates">
<div class="calendarCell"><b>M</b></div>
<div class="calendarCell"><b>T</b></div>
<div class="calendarCell"><b>W</b></div>
<div class="calendarCell"><b>T</b></div>
<div class="calendarCell"><b>F</b></div>
<div class="calendarCell"><b>S</b></div>
<div class="calendarCell"><b>S</b></div>
<div class="clearLeft"></div>
</div>
<div class="calendar">
';
if($start > 5){ $rows = 6; }else {$rows = 5; }
for($i = 1; $i <= $rows; $i++){
for($x = 1; $x <= 7; $x++){
if(($counter - $start) < 0){
$date = (($lastmonth - $laststart) + $counter);
$class = 'calendarBlank';
}else if(($counter - $start) >= $days){
$date = ($nextMonthCounter);
$nextMonthCounter++;
$class = 'calendarBlank';
}else if($counter <= $today){
$date = ($counter - $start + 1);
$class = 'calendarBlank';
}else {
$date = ($counter - $start + 1);
if($today == $counter - $start + 1){
$class = 'calendarToday';
}
}
echo '<div class="calendarCell '.$class.'">'.$date.'</div>';
$counter++;
$class = '';
}
}
echo '
<div class="clearLeft"></div>
</div>
<div class="calendarNavigation">
<div class="floatLeft">« Previous Month</div>
<div class="floatRight">Next Month »</div>
<div class="clearBoth"></div>
</div>
';
?>
Can anyone tell me how to block out everything previous to today's date?
Also, as you can see, I'd like to have a next & previous months navigation but I don't know how to get the navigation to refresh the php script with the relevant month information. Any help on this would be hugely appreciated too

Why dun you simply do this?
$currDay = date("j"); //at top of your code
and then in loop.
if((int)$currDay > (int)$date) {
$class ='calendarBlank';
}
This will do.
PS. Lemme know if you need complete code.

Related

Why wont the chosen option reflect in the PHP code I wrote?

Basically it's supposed to get the user submitted value of the array size, and the method they want to calculate with the array from the drop down. the php successful gets the code from the array size but always sees the field with the dropdown as "mean" no matter which I select.
forms5.html:
`<html>
<head>
</head>
<body style="background-color: rgb(192, 192, 192);">
<div class="container" style="background-color: rgb(165, 165, 165); width: 575px; height: 250px; border: ridge; border-color: rgb(209, 209, 209);">
<form name = "form1" method = "get" action = "actions_5.php">
<div class = "form-group" style=" padding-left: 10px; padding-right: 10px; padding-top: 10px;">
<label><h2>Enter size of an array</h2></label> <br>
<input type = "number" name = "array_size" placeholder="Type in an integer">
</div>
<br>
<div style="padding-left: 10px; padding-right: 10px;">
<label><b>Select an option</b></label>
<select name = "option" class="form-control">
<option value="mean">Calculate Mean</option>
<option value="median">Calculate Median</option>
<option value="mode">Calculate Mode</option>
</select>
</div>
<div style="padding: 10px;">
<input type="submit" class="btn btn-primary">
</div>
</form>
</div>
</body>
</html>'
actions_5.php:
'<?php
session_start();
echo "<html>";
echo "<head>";
echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
';
echo "</head>";
echo "<body style='background-color: lightgray'>";
//store variables
$choice = $_GET['option'];
$size = $_GET['array_size'];
//create array
for($i = 0; $i < $size; $i++) {
$array[$i] = mt_rand(1,10);
}
echo "<div style = 'color: green; padding-top: 160px'><center><h3>Initialized array --><h3></center></div>";
echo "<br>";
echo"<center><div style = 'color: red; font-size: 35px; padding-top: 10px'>";
for($i = 0; $i < $size; $i++) {
echo"<b>$array[$i] </b>";
}
echo"</div></center>";
echo"<br>";
//if statements
echo"<center><div style = padding=top: 10px; front-size: 35px>";
if($choice = "mean") {
$mean = array_sum($array) / count($array);
echo"<p style = 'color:crimson'><b>Mean = $mean</b></p>";
} else if($choice = "mode") {
sort($array);
sort($array, $size);
$max = 1;
$mode = $array[0];
$current = 1;
for($i = 0; $i < $size; $i++){
if($array[$i] == $array[$i] - 1){
$current++;
}
else {
if($current > $max) {
$max = $current;
$mode = $array[$i - 1];
}
$current = 1;
}
}
if($current > $max) {
$max = $current;
$mode = $array[$size - 1];
}
if($max = 1) {
echo"<p style = 'color:teal'><b>There is no mode in the set.</b></p>";
} else{
echo"<p style = 'color:teal'><b>Mode = $mode</b></p>";
}
} else {
rsort($array);
$n = count($array) / 2;
$median = $array($n);
echo"<p style = 'color:blue'><b>Median = $median</b></p>";
}
echo"</div></center>";
echo "</body>";
echo "</html>";
?>'

PHP calendar to block some not available dates

I'm designing a little PHP calendar for a little booking system. The final feature is to block some not available dates, that I have stored in a PHP array. What is the best way to achieve this? Please I need some recommendations about how to do this. Thanks
// Set your timezone!!
date_default_timezone_set('Europe/Madrid');
// Get prev & next month
if (isset($_GET['ym'])) {
$ym = $_GET['ym'];
} else {
// This month
$ym = date('Y-m');
}
// Check format
$timestamp = strtotime($ym . '-01'); // the first day of the month
if ($timestamp === false) {
$ym = date('Y-m');
$timestamp = strtotime($ym . '-01');
}
// Today (Format:2018-08-8)
$today = date('Y-m-j');
// Title (Format:August, 2018)
$title = date('F, Y', $timestamp);
// Create prev & next month link
$prev = date('Y-m', strtotime('-1 month', $timestamp));
$next = date('Y-m', strtotime('+1 month', $timestamp));
// Number of days in the month
$day_count = date('t', $timestamp);
// 1:Mon 2:Tue 3: Wed ... 7:Sun
$str = date('N', $timestamp);
// Array for calendar
$weeks = [];
$week = '';
// Add empty cell(s)
$week .= str_repeat('<td></td>', $str - 1);
for ($day = 1; $day <= $day_count; $day++, $str++) {
$date = $ym . '-' . $day;
if ($today == $date) {
$week .= '<td class="today">';
} else {
$week .= '<td>';
}
$week .= $day . '</td>';
// Sunday OR last day of the month
if ($str % 7 == 0 || $day == $day_count) {
// last day of the month
if ($day == $day_count && $str % 7 != 0) {
// Add empty cell(s)
$week .= str_repeat('<td></td>', 7 - $str % 7);
}
$weeks[] = '<tr>' . $week . '</tr>';
$week = '';
}
}
if I have an array in php with dates in this format "2020-08-12" that must be not available or not selectable how can I do.
here html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Calendar</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<style>
.container {
font-family: 'Montserrat', sans-serif;
margin: 60px auto;
}
.list-inline {
text-align: center;
margin-bottom: 30px;
}
.title {
font-weight: bold;
font-size: 26px;
}
th {
text-align: center;
}
td: {
height: 50px;
}
td:hover{
background-color: blue;
}
th:nth-of-type(6), td:nth-of-type(6) {
color: blue;
}
th:nth-of-type(7), td:nth-of-type(7) {
color: red;
}
.today {
background-color: red;
}
</style>
</head>
<body>
<div class="container w-50">
<ul class="list-inline">
<li class="list-inline-item">< prev</li>
<li class="list-inline-item"><span class="title"><?= $title; ?></span></li>
<li class="list-inline-item">next ></li>
</ul>
<p class="text-right">Hoy</p>
<table class="table table-bordered">
<thead>
<tr>
<th>LU</th>
<th>MA</th>
<th>MI</th>
<th>JU</th>
<th>VI</th>
<th>SA</th>
<th>DO</th>
</tr>
</thead>
<tbody>
<?php
foreach ($weeks as $week) {
echo $week;
}
?>
</tbody>
</table>
</div>
</body>
</html>
For every <td> that you output, check if its date is in your list of unavailable dates and output a class name so you can target it with CSS.
Change this code:
if ($today == $date) {
$week .= '<td class="today">';
} else {
$week .= '<td>';
}
$week .= $day . '</td>';
To this:
$classes = []; // assume
if ( in_array( $date, $unavailable_dates ) ) {
$classes[] = 'unavailable';
}
if ($today == $date) {
$classes[] = 'today';
}
$week .= '<td class="' . join(' ', $classes ) . '"></td>';
This assumes the array of unavailable dates is stored in $unavailable_dates, e.g. ['2020-08-10', '2020-08-12', '2020-08-17'].

How do I align a list of links/picture on the right side of the page, and stop them from overlapping?

I want to generate a list of links to other pages for my website (using a mix of PHP/HTML/CSS) and align them on the right side of the page without them overlapping. I am able to generate the links/pictures, but the problem I am having is they overlap on top of each other when I try to use position absolute.
<style>
body{
background: lightblue;
margin: 25px;
}
.title{
font-size: 20px;
}
.recipe{
width: 60%;
}
.related{
position: absolute;
float: right;
right: 10px;
width: 25%;
list-style-position: inside;
}
.a{
float: right;
right: 5px;
}
.relatedImages{
}img{
width: 15%;
height: 17%;
}
</style>
<title><?php $recipeInfo['title']; ?></title>
<body>
<br>
<?php
//Title and image of recipe
echo '<br><br><div class="title">' .$recipeInfo['title']. '</div><br>
<div class="mainImage"><image src="' . $recipeInfo['image']. '"> </div>
<br><h2> Ingredients </h2>';
//Unfinished (Needs to be styled correctly)
//Generating related links with clickable images
for($r = 0; $r < $relatedLinks[$r]; $r++){
echo '<div class = "related">
<a href = "recipeInfo.php?id='.$relatedLinks[$r]['id']. '">'.$relatedLinks[$r]['title'].'<br>
<image src = "https://spoonacular.com/recipeImages/' . $relatedLinks[$r]['image'] . '"></a>
<br>
</div>';
};
;
//Loop that generates a list of the ingredients used
for($i = 0; $i < $recipeInfo['extendedIngredients'][$i]; $i++){
$amount = $recipeInfo['extendedIngredients'][$i]['amount'];
$unit = $recipeInfo['extendedIngredients'][$i]['unit'];
$ingrName = $recipeInfo['extendedIngredients'][$i]['name'];
echo '<div class = "ingredients">' . $amount , " " , $unit , " " , $ingrName .' </div>';
}
//Instructions with error handling for no instructions found
$instructions = $recipeInfo['instructions'];
if($instructions == ""){
$instructions = "Whoops, there are no available instructions for this recipe.";
}
echo '<br><h2> Insructions </h2>
<div class="recipe">' . $instructions . '</div><br>';
//Unfinished, but will hopefully print a better list of instructions than just a dense paragraph
//for($j = 0; $j < sizeOf($recipeInstr); $j++){
// echo '<h3>' .$recipeInstr[$j]['name'].'</h3>';
// for($n = 0; $n < $recipeInstr[$j]['steps']; $n++){
// echo '<div class="instruction">'. $n , " " , $recipeInstr[$j]['steps'][$n]['step'] . '<div>';
// }
//}
?>
</body>
</html>
The intended effect I am going for is one similar to how youtube has related videos on the right side of the page.
Well cou could try this code:
<body>
<br>
<div class="maincontent">
<div class="main">
<?php
//Title and image of recipe
echo '<br><br><div class="title">' .$recipeInfo['title']. '</div><br>
<div class="mainImage"><image src="' . $recipeInfo['image']. '"> </div>
<br><h2> Ingredients </h2>';
//Loop that generates a list of the ingredients used
for($i = 0; $i < $recipeInfo['extendedIngredients'][$i]; $i++){
$amount = $recipeInfo['extendedIngredients'][$i]['amount'];
$unit = $recipeInfo['extendedIngredients'][$i]['unit'];
$ingrName = $recipeInfo['extendedIngredients'][$i]['name'];
echo '<div class = "ingredients">' . $amount , " " , $unit , " " , $ingrName .' </div>';
}
//Instructions with error handling for no instructions found
$instructions = $recipeInfo['instructions'];
if($instructions == ""){
$instructions = "Whoops, there are no available instructions for this recipe.";
}
echo '<br><h2> Insructions </h2>
<div class="recipe">' . $instructions . '</div><br>';
//Unfinished, but will hopefully print a better list of instructions than just a dense paragraph
//for($j = 0; $j < sizeOf($recipeInstr); $j++){
// echo '<h3>' .$recipeInstr[$j]['name'].'</h3>';
// for($n = 0; $n < $recipeInstr[$j]['steps']; $n++){
// echo '<div class="instruction">'. $n , " " , $recipeInstr[$j]['steps'][$n]['step'] . '<div>';
// }
//}
?>
</div>
<div class="sidelinks">
<?php
//Unfinished (Needs to be styled correctly)
//Generating related links with clickable images
for($r = 0; $r < $relatedLinks[$r]; $r++){
echo '<div class = "related">
<a href = "recipeInfo.php?id='.$relatedLinks[$r]['id']. '">'.$relatedLinks[$r]['title'].'<br>
<image src = "https://spoonacular.com/recipeImages/' . $relatedLinks[$r]['image'] . '"></a>
<br>
</div>';
};
;
</div>
</div>
</body>
</html>
and css code:
<style>
.maincontent {
display: grid;
grid-template-columns: 70% 30%;
}
body{
background: lightblue;
margin: 25px;
}
.title{
font-size: 20px;
}
.recipe{
width: 60%;
}
.related{
list-style-position: inside;
}
.a{
float: right;
right: 5px;
}
.relatedImages{
}img{
width: 15%;
height: 17%;
}
</style>
this should work, i couldnt test it

Show calendar from custom custom date

Hii i am working on portal which requires calendar from custom dates like from 14 Jul to 14 Aug.I have made a demo which starts properly i.e.if 14th july starts from Thursday but not ending at sunday which is on 14 aug. Take a look what i have done
function getCalender($year = '',$month = '')
{
$startDate = "2016-07-03";
$endDate = "2016-07-31";
$dateYear = ($year != '')?$year:date("Y");
$dateMonth = ($month != '')?$month:date("m");
$date = $dateYear.'-'.$dateMonth.'-01';
$currentMonthFirstDay = date("N",strtotime($date));
$startDateFrom = date("N",strtotime($startDate));
$endDateFrom = date("N",strtotime($endDate));
$timestamp = strtotime($startDate);
$dayCount = date("d", $timestamp);
$timestamp1 = strtotime($endDate);
$dayCountend = date("d", $timestamp1);
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
//$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
//$boxDisplay = 29
?>
<div id="calender_section">
<h2>
<!--<<-->
<select name="month_dropdown" class="month_dropdown dropdown"><?php echo getAllMonths($dateMonth); ?></select>
<select name="year_dropdown" class="year_dropdown dropdown"><?php echo getYearList($dateYear); ?></select>
<!-->>-->
</h2>
<div id="event_list" class="none"></div>
<!--For Add Event-->
<div id="event_add" class="none">
<p>Add Event on <span id="eventDateView"></span></p>
<p><b>Event Title: </b><input type="text" id="eventTitle" value=""/></p>
<input type="hidden" id="eventDate" value=""/>
<input type="button" id="addEventBtn" value="Add"/>
</div>
<div id="calender_section_top">
<ul>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
<li>Sun</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
for($cb=1;$cb<=$dayCountend;$cb++){
//echo $cb;
if(($cb >= $startDateFrom) && $cb<=$dayCountend)
{
/*if(($cb >= $currentMonthFirstDay+1 || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay)){*/
//Current date
$currentDate = $dateYear.'-'.$dateMonth.'-'.$dayCount;
$currentdate = date("D M j",strtotime($currentDate));
$eventNum = 0;
//Include db configuration file
include 'dbConfig.php';
//Get number of events based on the current date
$result = $db->query("SELECT title FROM events WHERE date = '".$currentDate."' AND status = 1");
$eventNum = $result->num_rows;
//Define date cell color
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
echo '<li date="'.$currentDate.'" class="grey date_cell">';
}elseif($eventNum > 0){
echo '<li date="'.$currentDate.'" class="light_sky date_cell">';
}else{
echo '<li date="'.$currentDate.'" class="date_cell">';
}
//Date cell
echo '<span>';
echo $cb;
echo '</span>';
//Hover event popup
/*echo '<div id="date_popup_'.$currentDate.'" class="date_popup_wrap none">';
echo '<div class="date_window">';
echo '<div class="popup_event">Events ('.$eventNum.')</div>';
echo ($eventNum > 0)?'view events<br/>':'';
//For Add Event
echo 'add event';
echo '</div></div>';
echo '</li>';*/
$dayCount++;
?>
<?php }else{ ?>
<li><span> </span></li>
<?php } } ?>
</ul>
</div>
</div>
<?php
}
?>
I tried for your code and i found one logic i took start date and end date from the user and made the array of the dates which are present between two.
Then calendar should start from for ex. 3 Jul 2016 the day is Sunday for that i inserted - upto first date. Check below what i have done
function getCalender($year = '',$month = '',$startDate = '',$endDate = '')
{
$finalArray = array();
$startDate = "2016-07-03";
$endDate = "2016-08-31";
$date1 = createDateRangeArray('2016-07-03 ','2016-08-31');
//$date = $dateYear.'-'.$dateMonth.'-01';
$startDateFrom = date("N",strtotime($startDate));
$endDateFrom = date("N",strtotime($endDate));
//Take the day from the date
$timestamp = strtotime($startDate);
$dayCount = date("d", $timestamp);
//Take the month from the date
$timestampend = strtotime($endDate);
$dayCountend = date("d", $timestampend);
//Take the month from the date
$timestampmonth = strtotime($startDate);
$monthstart = date("m", $timestampmonth);
//Take the month from the date
$timestampmonthend = strtotime($endDate);
$monthend = date("m", $timestampmonthend);
//Take the year from the start date
$yearstart = strtotime($startDate);
$yearofStart = date("y", $yearstart);
//Take the year from the end date
$yearend = strtotime($endDate);
$yearofEnd = date("y", $yearend);
//cal difference between start date and month
$differenceStartDate = $dayCount - 1;
//cal difference between end date and month
$totalDaysOfMonthEnd = cal_days_in_month(CAL_GREGORIAN,$monthend,$yearofEnd);
$totalDaysOfMonthStart = cal_days_in_month(CAL_GREGORIAN,$monthstart,$yearofEnd);
if($monthstart == $monthend)
{
echo "Show one month calendar";
}
else
{
$diffmonth = $monthend-$monthstart;
}
$differenceStartDate = $dayCountend - $totalDaysOfMonth;
for($i=1;$i<$startDateFrom;$i++)
{
$date[] = '-';
}
array_push($date,$date1);
for($j=0;$j<count($date);$j++)
{
if(strlen($date[$j])==1)
{
array_push($finalArray,$date[$j]);
}
else
{
for($k=0;$k<count($date[$j]);$k++)
{
array_push($finalArray,$date[$j][$k]);
}
}
}
print_r($finalArray);
$timestamp1 = strtotime($endDate);
$dayCountend = date("d", $timestamp1);
$now = strtotime($startDate);
$your_date = strtotime($endDate);
$datediff = $your_date - $now;
$diff= floor($datediff/(60*60*24));
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
//$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
$boxDisplay = $diff;
?>
<div id="calender_section">
<h2>
<!--<<-->
<!-- <select name="month_dropdown" class="month_dropdown dropdown"><?php echo getAllMonths($dateMonth); ?></select>
<select name="year_dropdown" class="year_dropdown dropdown"><?php echo getYearList($dateYear); ?></select>-->
<!-->>-->
</h2>
<div id="event_list" class="none"></div>
<!--For Add Event-->
<div id="event_add" class="none">
<p>Add Event on <span id="eventDateView"></span></p>
<p><b>Event Title: </b><input type="text" id="eventTitle" value=""/></p>
<input type="hidden" id="eventDate" value=""/>
<input type="button" id="addEventBtn" value="Add"/>
</div>
<div id="calender_section_top">
<ul>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
<li>Sun</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
for($cb=0;$cb<count($finalArray);$cb++)
{
//echo $cb;
$date = $finalArray[$cb];
$month = strtotime($date);
$month = date("m", $month);
if(($cb >= $startDateFrom -1))
{
/*if(($cb >= $currentMonthFirstDay+1 || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay)){*/
//Current date
$currentDate = $finalArray[$cb];
//$currentdate = date("D M j",strtotime($currentDate));
$eventNum = 0;
//Include db configuration file
//Define date cell color
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
echo '<li date="'.$currentDate.'" class="grey date_cell">';
echo '<select name="select"></select>
<option value="0"></option>';
}elseif($eventNum > 0){
echo '<li date="'.$currentDate.'" class="light_sky date_cell">';
echo '<select name="select"></select>
<option value="0"></option>';
}else{
echo '<li date="'.$currentDate.'" class="date_cell">';
echo '<select name="select"></select>
<option value="0"></option>';
}
//Date cell
echo '<span>';
echo $currentDate;
echo '</span>';
$dayCount++;
?>
<?php }else{ ?>
<li><span> </span></li>
<?php } } ?>
</ul>
</div>
</div>
<?php
}
function createDateRangeArray($strDateFrom,$strDateTo)
{
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
?>
Take a look at a code and you will understand that easily
The answer given by #BeDeveloper is fine.I made something like below which automatically disable all the other dates for ex.if date 3 it will disable 1 and 2
<style>
/* calendar */
h1 { font-family: calibri; font-size: 20px; color: #6d6d6d}
table.calendar { border-left:1px solid #999; }
tr.calendar-row { }
td.calendar-day { min-height:80px; font-size:11px; position:relative; } * html div.calendar-day { height:80px; }
td.calendar-day:hover { background:#eceff5; }
td.calendar-day-np { background:#eee; min-height:80px; } * html div.calendar-day-np { height:80px; }
td.calendar-day-head { background:#ccc; font-weight:bold; text-align:center; width:120px; padding:5px; border-bottom:1px solid #999; border-top:1px solid #999; border-right:1px solid #999; }
div.day-number { background:#999; padding:5px; color:#fff; font-weight:bold; float:right; margin:-5px -5px 0 0; width:20px; text-align:center; }
/* shared */
td.calendar-day, td.calendar-day-np { width:120px; padding:5px; border-bottom:1px solid #999; border-right:1px solid #999; }
</style>
<?php
/* draws a calendar */
function draw_calendar($month,$year,$startDate,$endDate){
$startDate = date('Y-m-d',$startDate);
$endDate = date('Y-m-d',$endDate);
$timestamp = strtotime($startDate);
$dayCountstart = date("d", $timestamp);
$timestamp = strtotime($endDate);
$dayCountend = date("d", $timestamp);
$timestampmonth = strtotime($startDate);
$monthstart = date("m", $timestampmonth);
$timestampmonthend = strtotime($endDate);
$monthend = date("m", $timestampmonthend);
$yearend = strtotime($endDate);
$yearofEnd = date("y", $yearend);
$dayMinus = $dayCountstart - 01;
$totalDaysOfMonthEnd = cal_days_in_month(CAL_GREGORIAN,$monthend,$yearofEnd);
$dayEndMinus = $totalDaysOfMonthEnd - $dayCountend;
/* draw table */
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
/* table headings */
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
/* days and weeks vars now ... */
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
/* row for week one */
$calendar.= '<tr class="calendar-row">';
/* print "blank" days until the first of the current week */
for($x = 0; $x < $running_day; $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
$days_in_this_week++;
endfor;
/* keep going with days.... */
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
$calendar.= '<td class="calendar-day">';
/* add in the day number */
if($monthstart == $month)
{
if($list_day <= $dayMinus)
{
$calendar.= '<div class="day-number123">'.$list_day.'</div>';
}
else
{
$calendar.= '<div class="day-number">'.$list_day.'</div>';
}
}
else
{
if($monthend == $month)
{
if($list_day <= $dayCountend)
{
$calendar.= '<div class="day-number">'.$list_day.'</div>';
}
else
{
$calendar.= '<div class="day-number123">'.$list_day.'</div>';
}
}
else
{
$calendar.= '<div class="day-number">'.$list_day.'</div>';
}
}
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$calendar.= str_repeat('<p> </p>',2);
$calendar.= '</td>';
if($running_day == 6):
$calendar.= '</tr>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<tr class="calendar-row">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
/* finish the rest of the days in the week */
/* if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
endfor;
endif;*/
/* final row */
$calendar.= '</tr>';
/* end the table */
$calendar.= '</table>';
/* all done, return result */
return $calendar;
}
/* sample usages */
/*echo '<h2>July 2009</h2>';
echo draw_calendar(7,2009);
echo '<h2>August 2009</h2>';
echo draw_calendar(8,2009);
*/
$start = $startDate= $month = strtotime('2016-02-02');
$end = $endDate = strtotime('2016-03-03');
while($month < $end)
{
//$a = date('m Y', $month), PHP_EOL;
$startDate = $start;
$endDate = $end;
$newMonthInRange = date('m', $month);
$newYearInRange = date('Y', $month);
$newMonthInRangeTitle = date('F Y', $month);
$month = strtotime("+1 month", $month);
echo "<h1>".$newMonthInRangeTitle."</h1>";
echo draw_calendar($newMonthInRange,$newYearInRange,$startDate,$endDate);
}
?>

php expiry date traffic light system

I am working on a traffic light system. It's in a bit of a mess and it's not working the way it should.
My aim is to get the system working like so;
In the database there are dates of when a supplier's insurance is due to expire. If the date of expiry is 30 days away or less then I want these dates to be pulled through and echoed out, but others which expire after 30 days should not be shown.
At the moment it also gives the number of days until the expiry date, but this doesn't work correctly, so say today was the 2nd of May and tomorrow is the 3rd; the insurance document is due to expire on the 3rd, so it should say insurance expires tomorrow. This is currently not working correctly and I'm getting something like '2 days' till expiry instead of 'expires tomorrow'
Like wise if the insurance was due to expire today it should say expires today but its not getting the days right.
Also, i have designed diffrent coloured div tags to show as a sort of traffic light signal depending on which dates the insurance docs expire. If a document is due to expire within 30 to 20 days i want my green div to display, else if a document is due to expire in 19-7 days i want it to show as amber, if a document is due to expire 7-0 days or is over due it should be red.
Here is my code, please can someone show me how i could improve it to do what i need it to do, thanks
CODE:
<?php include 'config.php';
$data = mysql_query("SELECT *, TIMESTAMPDIFF(DAY, insurance_date, NOW()) AS expire_date FROM supplier_stats")
or die(mysql_error());
echo "<table class=\"table\" style=\"width:995px; font-family: 'Lucida Grande', Tahoma, Verdana, Arial, sans-serif;
font-size:11px;\" >
<tr>
<td style=\"width:100px;\">ID:</td><td>Company Name:</td><td>Company Reg No:</td><td>Owner:</td><td style=\"width:200px;\">Note:</td><td style=\"width:100px;\">Date:</td><td>Status:</td></tr>";
while($row = mysql_fetch_array( $data )) {
$days = $row['expire_date'] -1;
echo "<tr><td style=\"width:100px;\"><p>".$row['id'] . "</p></td>";
echo "<td style=\"width:150px;\"><p>".$row['company_name'] . "</p></td>";
echo "<td style=\"width:150px;\"><p>".$row['company_reg_number'] . "</p></td>";
echo "<td style=\"width:100px;\"><p>".$row['owner'] . "</p></td>";
if ($days > 0) {
echo "<td style=\"width:200px;\"><p>Insurance expires in <font color=\"red\">{$row['expire_date']} day(s)!</font></p></td>";
} else {
$when = $days*-1;
echo "<td style=\"width:200px;\"><p>Insurance expires";
if ($when > 1){
echo " in <font color=\"red\">{$when} days</font></p></td>";
} elseif ($when < 1) {
echo "<font color=\"red\"> tomorrow!</font></td>";
}
elseif ($when == 0)
{
echo " today!</font></p></td>";
}
echo "<td>";
echo date('d/m/Y',strtotime($row['insurance_date']));
echo"</td>";
}
if ($when >= 20){
echo "<td style=\"width:150px;\"><div class=\"green_light\"></div></td>";
}
if ($when >= 7){
echo "<td style=\"width:150px;\"><div class=\"amber_light\"></div></td>";
}
if ($when <= 7){
echo "<td style=\"width:150px;\"><div class=\"red_light\"></div></td>";
}
echo "<tr>";
}
echo "</table>"; //Close the table in HTML
?>
change the query to accurately reflect the days before the expiry_date then it should simplify the checking. The query below truncates to the day and gives accurate days_before_expires as positive numbers.
positive numbers are days before. so +1 means ends tomorrow.
zero means ends today
negative numbers means it has expired.
SELECT *, TIMESTAMPDIFF(DAY, CURRENT_DATE(), DATE(insurance_date)) AS days_before_expires FROM supplier_stats
Converted to 'mysqli'.
All the code has been tested. It implements the 'traffic light' status. I have changed the formatting code to try and make it more maintainable by using functions to calculate an 'urgency indicator'. All the formatting is now done using css.
<!DOCTYPE HTML">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF8">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title>23424062/php-expiry-date-traffic-light-system</title>
<style type="text/css">
table {
width:995px;
font-family: 'Lucida Grande', Tahoma, Verdana, Arial, sans-serif;
font-size:11px;
}
th {text-align: left; }
.width_small {
width: 100px;
}
.width_medium {
width: 150px;
}
.width_large {
width: 200px;
}
.urgency_1 {
display: inline-block;
width: 6em;
background-color: green;
color: yellow;
padding-left: 1em;
}
.urgency_2 {
display: inline-block;
width: 6em;
background-color: orange;
padding-left: 1em;
}
.urgency_3 {
display: inline-block;
width: 6em;
background-color: red;
color: yellow;
padding-left: 1em;
}
.green_light {
width: 3em;
background-color: green;
}
.amber_light {
width: 3em;
background-color: orange;
}
.red_light {
width: 3em;
background-color: red;
}
</style>
</head>
<body>
<?php
$mysqli = new mysqli('localhost', 'test', 'test', 'testmysql');
$data = $mysqli->query("SELECT *, "
." TIMESTAMPDIFF(DAY, CURRENT_DATE(), DATE(insurance_date)) AS days_before_expires, "
." DATE(insurance_date) as insurance_day "
." FROM supplier_stats order by DATE(insurance_date)")
or die(mysql_error());
?>
<table>
<tr><th class="width_small">ID:</th><th>Company Name:</th><th>Company Reg No:</th><th>Owner:</th><th class="width_large">Note:</th><th class="width_small">Date:</th><th>Status:</th></tr>
<?php while($row = $data->fetch_array()): ?>
<?php $daysLeft = $row['days_before_expires']; ?>
<?php $urgency = getUrgency($daysLeft); ?>
<?php $cssTrafficLight = selectUrgencyLit($row['days_before_expires'],
array('', 'green_light', 'amber_light', 'red_light')); ?>
<?php $cssUrgency = selectUrgencyLit($row['days_before_expires'],
array('urgency_0', 'urgency_1', 'urgency_2', 'urgency_3')); ?>
<?php $daysLeftLit = getDaysLeftLiteral($daysLeft); ?>
<tr><td class="width_small"><p><?= $row['id'] ?></p></td>
<td class="width_medium"><p><?= $row['company_name'] ?></p></td>
<td class="width_medium"><p><?= $row['company_reg_number'] ?></p></td>
<td class="width_small"><p><?= $row['owner'] ?></p></td>
<td class="width_large"><?= $daysLeftLit; ?></td>
<td class="width_small"><?= date('d/m/Y',strtotime($row['insurance_day'])) ?></td>
<td class="width_medium"><div class="<?= $cssTrafficLight?>"> </div></td>
<tr>
<?php endwhile; ?>
</table> <!-- Close the table in HTML -->
</body>
</html>
<?php
/*
* To tidy the code up and hopefully make it easier to maintain we need
* a couple of functions...
*
* How about assigning an 'urgency level' to each record depending on the
* days left before the expiry date. The level is as follows:
*
* 0 => not urgent (more than 20 days)
* 1 => need to pay attention (14 - 20)
* 2 => soon (7 - 13)
* 3 => now (0 - 6)
*/
function getUrgency($daysLeft)
{
if ($daysLeft >= 21 || $daysLeft < 0) { return 0; }
if ($daysLeft >= 14 && $daysLeft <= 20) { return 1; }
if ($daysLeft >= 7 && $daysLeft <= 13) { return 2; }
return 3;
}
// return a literal depending on the urgency
function selectUrgencyLit($daysLeft, array $litArray)
{
$urgency = getUrgency($daysLeft);
if (!empty($litArray[$urgency])) {
return $litArray[$urgency];
}
return '';
}
// return the days left literal
function getDaysLeftLiteral($daysLeft)
{
$urgency = getUrgency($daysLeft);
if ($urgency <= 0) {
return ' ';
}
$text = "Insurance Expires: <div class=\"urgency_{$urgency}\">";
// set the day literal to be shown
if ($daysLeft == 0) { $dayLit = 'today'; }
elseif ($daysLeft == 1) { $dayLit = 'tomorrow'; }
elseif ($daysLeft >= 0 && $daysLeft <= 20) { $dayLit = "in {$daysLeft} days"; }
else { $dayLit = ' '; }
return $text . $dayLit .'</div>';
}

Categories