How to display days in a grid by weeks in php? - php

I am trying to display the days of a month in a grid-like or table like form. I was considering using Bulma or bootstrap to handle the grid/tables. The grid is based on 5 rows and 7 columns. I can't figure out how to go about implementing the correct days of the week. Each week should be grouped by a div with dates inside the div. This is what I have so far:
<?php
$row = '';
$startDate = 12/30/2018;
$numDays = 35;
$datesArr = array();
$weekCounter = 1;
for ($i = 0; $i <= numDays; i++) {
$row .= '<div>';
$date = date('m/j/Y', strtotime("$startDate +$i days"));
$datesArr[] = $date;
if ($i % 8 == 0) {
$row .= '<p>Week ' . $weekCounter++ . '</p>';
} else {
$row .= '<p>'.$date . ' - ' . date('l'), strtotime($date)). '</p>';
}
$row .= '</div>';
}
echo $row;
?>
This is my current output:
Week 1
12/31/2018-Monday
01/1/2019-Tuesday
01/2/2019-Wednesday
01/3/2019-Thursday
01/4/2019-Friday
01/5/2019-Saturday
01/6/2019-Sunday
Week 2
01/8/2019-Tuesday
01/9/2019-Wednesday
01/10/2019-Thursday
01/11/2019-Friday
01/12/2019-Saturday
01/13/2019-Sunday
01/14/2019-Monday
Week 3
01/16/2019-Wednesday
01/17/2019-Thursday
01/18/2019-Friday
01/19/2019-Saturday
01/20/2019-Sunday
01/21/2019-Monday
01/22/2019-Tuesday
Week 4
01/24/2019-Thursday
01/25/2019-Friday
01/26/2019-Saturday
01/27/2019-Sunday
01/28/2019-Monday
01/29/2019-Tuesday
01/30/2019-Wednesday
Week 5
02/1/2019-Friday
02/2/2019-Saturday
02/3/2019-Sunday

<?php
$row = '';
$startDate = '12/30/2018';
$numDays = 35;
$datesArr = array();
$weekCounter = 1;
for ($i = 0; $i <= $numDays; $i++) {
$date = date('m/j/Y', strtotime("$startDate +$i days"));
$datesArr[] = $date;
// New div at start of week
if (date("l", strtotime($date)) == "Sunday") {
$row .= "<div style=\"float: left; margin: 10px;\">";
$row .= '<p>Week ' . $weekCounter++ . '</p>';
}
$row .= '<p>'. $date . ' - ' . date("l", strtotime($date)) . '</p>';
// close div at end of week
if (date("l", strtotime($date)) == "Saturday") {
$row .= "</div>";
}
}
echo $row;
?>

You can also consider using jQuery UI Datepicker. You can use AJAX to get a start date and number of days. Then draw the calendar.
$(function() {
function getDateInfo() {
$.getJSON("dateInfo.php", function(data){
drawCal(data.startDate, data.numDays, $(".calendar"));
})
}
function drawCal(sd, nd, tObj) {
var format = "mm/dd/yy";
var min = $.datepicker.parseDate(format, sd);
var max = new Date();
max.setDate(min.getDay() + nd);
console.log(sd, max);
tObj.html("");
tObj.datepicker({
dateFormat: format,
minDate: min,
maxDate: max,
numberOfMonths: [3, 1]
});
}
drawCal("12/31/2018", 35, $(".calendar"));
});
.ui-datepicker-group {
width: 100%;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="calendar"></div>

Related

Get week number for given month of year for presentation on calendar

I'm creating a calendar with Sunday being the start of each week and I want to present the week number of the year before each row of dates.
This is my calendar
my calendar
How can I add week numbers like this:
This is what I need
My code:
<?php
function generate_calendar($month, $year) {
$calendar = array();
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$first_day_of_month = date('w', strtotime("$year-$month-01"));
$week_number = 1;
$week = array();
// Determine the week number offset
$days_from_january_1st = strtotime("$year-01-01");
$days_to_first_day_of_month = strtotime("$year-$month-01");
$week_number_offset = floor(($days_to_first_day_of_month - $days_from_january_1st) / 604800);
// Check if the last week of the previous month is full (7 days)
$last_week_of_previous_month = $week_number_offset;
if ($month > 1) {
$previous_month = $month - 1;
$previous_month_year = $year;
$previous_month_year = date("Y", strtotime("-1 month" , strtotime("$year-$month-01")));
$previous_month = date("n", strtotime("-1 month" , strtotime("$year-$month-01")));
if ($previous_month == 0) {
$previous_month = 12;
$previous_month_year = $year - 1;
}
$days_in_previous_month = cal_days_in_month(CAL_GREGORIAN, $previous_month, $previous_month_year);
$last_day_of_previous_month = date('w', strtotime("$previous_month_year-$previous_month-$days_in_previous_month"));
if ($last_day_of_previous_month == 6) {
$last_week_of_previous_month=$last_week_of_previous_month + 1;
} else {
// Check if the last week of the previous month only has a few days
$last_week_of_previous_month = $last_week_of_previous_month;
}
}
// Generate the previous month's days
for ($i = 1; $i <= $first_day_of_month; $i++) {
array_unshift($week, "");
}
// Generate the current month's days
for ($i = 1; $i <= $days_in_month; $i++) {
$week[] = $i;
if (count($week) == 7) {
$calendar[$week_number + $last_week_of_previous_month] = $week;
$week_number++;
$week = array();
}
}
// Generate the next month's days
$remaining_days = 7 - count($week);
for ($i = 1; $i <= $remaining_days; $i++) {
$week[] = '';
}
if (!empty($week)) {
$calendar[$week_number + $last_week_of_previous_month] = $week;
}
return $calendar;
}
$year = 2022;
echo "<table>\n";
echo " <tr>\n";
echo " <th colspan='3'>$year</th>\n";
echo " </tr>\n";
echo " <tr>\n";
for($i=1; $i<=12; $i++){
$month_name = date('F Y', strtotime("$year-$i-01"));
$calendar = generate_calendar($i, $year);
echo "<td>\n";
echo "<table>\n";
echo " <tr>\n";
echo " <th colspan='8'>$month_name</th>\n";
echo " </tr>\n";
echo " <tr>\n";
echo " <th>Week</th>\n";
echo " <th>Sun</th>\n";
echo " <th>Mon</th>\n";
echo " <th>Tue</th>\n";
echo " <th>Wed</th>\n";
echo " <th>Thu</th>\n";
echo " <th>Fri</th>\n";
echo " <th>Sat</th>\n";
echo " </tr>\n";
foreach ($calendar as $week_number => $week) {
echo " <tr>\n";
echo " <td>$week_number</td>\n";
foreach ($week as $day) {
if (empty($day)) {
echo " <td></td>\n";
} else {
echo " <td>$day</td>\n";
}
}
echo " </tr>\n";
}
echo "</table>\n";
echo "</td>\n";
if($i==3 || $i==6 || $i==9){
echo " </tr>\n";
echo " <tr>\n";
}
}
echo " </tr>\n";
echo "</table>\n";
?>
Trying to add week number which counts from first week of January (if last week of previous month is not full 7 days then first week of current month start from last week of previous month), but my code only count from first week of current month.
I managed to get the right result (as far as I tested) with IntlCalendar and its FIELD_WEEK_OF_YEAR constant instead of counting Sundays.
I did some refactoring of your function, but ran out of time to do a full reduction of the script (there may still be lines that can be simplified/condensed).
Code: (Demo)
function generate_calendar(int $month, int $year) {
$calendar = [];
$week_number = (IntlCalendar::fromDateTime ("$year-$month-01"))->get(IntlCalendar::FIELD_WEEK_OF_YEAR);
$month_start = new DateTime("$year-$month-01");
// Generate the previous month's days
if ($first_day = $month_start->format('w')) {
$week = array_fill(1, $first_day, '');
}
// Generate the current month's days
$days_in_month = $month_start->format('t');
for ($i = 1; $i <= $days_in_month; $i++) {
$week[] = $i;
if (count($week) == 7) {
$calendar[$week_number] = $week;
$week_number++;
$week = [];
}
}
if ($week) {
// Generate empty days for the next month
$calendar[$week_number] = array_pad($week, 7, '');
}
return $calendar;
}
I don't believe there is any way to set the start day of the week in the standard library of PHP without manual calculation, but you can do it easily with the intl library (make sure the intl PHP extension is enabled):
$cal = IntlGregorianCalendar::createInstance();
// Set start of week to Sunday
$cal->setFirstDayOfWeek(IntlGregorianCalendar::DOW_SUNDAY);
// Get week number of the year for the current date
$weekOfYear = intval(IntlDateFormatter::formatObject($cal, 'w'));
// Advance to the next week
$cal->add(IntlGregorianCalendar::FIELD_WEEK_OF_YEAR, 1);
// ect...

Calendar booking

I use script for booking and is work perfect but i dont know how to make some changes. Booking script have three files:
Over File calendar.php see calendar. I click on the day and I get free time to book.
I made that can be booked at least two slots and up to 4 but can not do to the reserved slots must be next to each other in order to reserve terms of half an hour or an hour continuously.
Example: i want reserved minimal 1 hour and max 2 hour continuously.
Can you help me to resolve this problem?
Second problem is name of day and months:
I tried despite all this change the names of days and months in the Spanish but I never could. Do you have a solution for this?
Now the names of days and months are displayed in English.
Calendar.php script is:
<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
include('php/connect.php');
include('classes/class_calendar.php');
$calendar = new booking_diary($link);
if(isset($_GET['month'])) $month = $_GET['month']; else $month = date("m");
if(isset($_GET['year'])) $year = $_GET['year']; else $year = date("Y");
if(isset($_GET['day'])) $day = $_GET['day']; else $day = 0;
// Unix Timestamp of the date a user has clicked on
$selected_date = mktime(0, 0, 0, $month, 01, $year);
// Unix Timestamp of the previous month which is used to give the back arrow the correct month and year
$back = strtotime("-1 month", $selected_date);
// Unix Timestamp of the next month which is used to give the forward arrow the correct month and year
$forward = strtotime("+1 month", $selected_date);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Calendar</title>
<link href="style.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Droid+Serif" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var check_array = [];
$(document).ready(function(){
$(".fields").click(function(){
dataval = $(this).data('val');
// Show the Selected Slots box if someone selects a slot
if($("#outer_basket").css("display") == 'none') {
$("#outer_basket").css("display", "block");
}
if(jQuery.inArray(dataval, check_array) == -1) {
check_array.push(dataval);
} else {
// Remove clicked value from the array
check_array.splice($.inArray(dataval, check_array) ,1);
}
slots=''; hidden=''; basket = 0;
cost_per_slot = $("#cost_per_slot").val();
//cost_per_slot = parseFloat(cost_per_slot).toFixed(2)
for (i=0; i< check_array.length; i++) {
slots += check_array[i] + '\r\n';
hidden += check_array[i].substring(0, 8) + '|';
basket = (basket + parseFloat(cost_per_slot));
}
// Populate the Selected Slots section
$("#selected_slots").html(slots);
// Update hidden slots_booked form element with booked slots
$("#slots_booked").val(hidden);
// Update basket total box
basket = basket.toFixed(2);
$("#total").html(basket);
// Hide the basket section if a user un-checks all the slots
if(check_array.length < 2)
$("#outer_basket").css("display", "none");
if(check_array.length > 4)
$("#outer_basket").css("display", "none");
});
$(".classname").click(function(){
msg = '';
if($("#name").val() == '')
msg += 'Please enter a Name\r\n';
if($("#email").val() == '')
msg += 'Please enter an Email address\r\n';
if($("#phone").val() == '')
msg += 'Please enter a Phone number\r\n';
if(msg != '') {
alert(msg);
return false;
}
});
// Firefox caches the checkbox state. This resets all checkboxes on each page load
$('input:checkbox').removeAttr('checked');
});
</script>
</head>
<body>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$calendar->after_post($month, $day, $year);
}
// Call calendar function
$calendar->make_calendar($selected_date, $back, $forward, $day, $month, $year);
?>
</body>
</html>
Script book_slots.php is:
<?php
include('php/connect.php');
if(isset($_POST['slots_booked'])) $slots_booked = mysqli_real_escape_string($link, $_POST['slots_booked']);
if(isset($_POST['name'])) $name = mysqli_real_escape_string($link, $_POST['name']);
if(isset($_POST['email'])) $email = mysqli_real_escape_string($link, $_POST['email']);
if(isset($_POST['phone'])) $phone = mysqli_real_escape_string($link, $_POST['phone']);
if(isset($_POST['booking_date'])) $booking_date = mysqli_real_escape_string($link, $_POST['booking_date']);
if(isset($_POST['cost_per_slot'])) $cost_per_slot = mysqli_real_escape_string($link, $_POST['cost_per_slot']);
$booking_array = array(
"slots_booked" => $slots_booked,
"booking_date" => $booking_date,
"cost_per_slot" => number_format($cost_per_slot, 2),
"name" => $name,
"email" => $email,
"phone" => $phone
);
$explode = explode('|', $slots_booked);
foreach($explode as $slot) {
if(strlen($slot) > 0) {
$stmt = $link->prepare("INSERT INTO bookings (date, start, name, email, phone) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $booking_date, $slot, $name, $email, $phone);
$stmt->execute();
} // Close if
} // Close foreach
print_r('<pre>');
print_r($booking_array);
print_r('</pre>');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Booking Confirmed</title>
<link href="style.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Droid+Serif" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<div class='success'>The booking has been made into the database.</div>
<p style='font-family:courier; font-size:13px; margin-top:25px'>
The booking has been inserted into the database.<br>
The array above shows you details of the $_POST.<br>
</p>
<p style='font-family:courier; font-size:13px; margin-top:25px'>
You might want to use this page to:
</p>
<ul style='font-family:courier; font-size:13px'>
<li>Redirect the user to a payment gateway (Paypal)</li>
<li>Simply show a confirmation page</li>
<li>Integrate with your basket</li>
</ul>
</body>
</html>
And class_calendar.php is:
<?php
class booking_diary {
// Mysqli connection
function __construct($link) {
$this->link = $link;
}
// Settings you can change:
// Time Related Variables
public $booking_start_time = "09:30"; // The time of the first slot in 24 hour H:M format
public $booking_end_time = "19:00"; // The time of the last slot in 24 hour H:M format
public $booking_frequency = 30; // The slot frequency per hour, expressed in minutes.
// Day Related Variables
public $day_format = 1; // Day format of the table header. Possible values (1, 2, 3)
// 1 = Show First digit, eg: "M"
// 2 = Show First 3 letters, eg: "Mon"
// 3 = Full Day, eg: "Monday"
public $day_closed = array("Saturday", "Sunday"); // If you don't want any 'closed' days, remove the day so it becomes: = array();
public $day_closed_text = "CLOSED"; // If you don't want any any 'closed' remove the text so it becomes: = "";
// Cost Related Variables
public $cost_per_slot = 20.50; // The cost per slot
public $cost_currency_tag = "£"; // The currency tag in HTML such as € £ ¥
// DO NOT EDIT BELOW THIS LINE
public $day_order = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
public $day, $month, $year, $selected_date, $back, $back_month, $back_year, $forward, $forward_month, $forward_year, $bookings, $count, $days, $is_slot_booked_today;
/*========================================================================================================================================================*/
function make_calendar($selected_date, $back, $forward, $day, $month, $year) {
// $day, $month and $year are the $_GET variables in the URL
$this->day = $day;
$this->month = $month;
$this->year = $year;
// $back and $forward are Unix Timestamps of the previous / next month, used to give the back arrow the correct month and year
$this->selected_date = $selected_date;
$this->back = $back;
$this->back_month = date("m", $back);
$this->back_year = date("Y", $back); // Minus one month back arrow
$this->forward = $forward;
$this->forward_month = date("m", $forward);
$this->forward_year = date("Y", $forward); // Add one month forward arrow
// Make the booking array
$this->make_booking_array($year, $month);
}
function make_booking_array($year, $month, $j = 0) {
$stmt = $this->link->prepare("SELECT name, date, start FROM bookings WHERE date LIKE CONCAT(?, '-', ?, '%')");
$this->is_slot_booked_today = 0; // Defaults to 0
$stmt->bind_param('ss', $year, $month);
$stmt->bind_result($name, $date, $start);
$stmt->execute();
$stmt->store_result();
while($stmt->fetch()) {
$this->bookings_per_day[$date][] = $start;
$this->bookings[] = array(
"name" => $name,
"date" => $date,
"start" => $start
);
// Used by the 'booking_form' function later to check whether there are any booked slots on the selected day
if($date == $this->year . '-' . $this->month . '-' . $this->day) {
$this->is_slot_booked_today = 1;
}
}
// Calculate how many slots there are per day
$this->slots_per_day = 0;
for($i = strtotime($this->booking_start_time); $i<= strtotime($this->booking_end_time); $i = $i + $this->booking_frequency * 60) {
$this->slots_per_day ++;
}
$stmt->close();
$this->make_days_array($year, $month);
} // Close function
function make_days_array($year, $month) {
// Calculate the number of days in the selected month
$num_days_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
// Make $this->days array containing the Day Number and Day Number in the selected month
for ($i = 1; $i <= $num_days_month; $i++) {
// Work out the Day Name ( Monday, Tuesday... ) from the $month and $year variables
$d = mktime(0, 0, 0, $month, $i, $year);
// Create the array
$this->days[] = array("daynumber" => $i, "dayname" => date("l", $d));
//$this->days[0] = array("daynumber" => 0, "dayname" => ("Ponedeljak"));
//$this->days[1] = array("daynumber" => 1, "dayname" => ("Utorak"));
//$this->days[2] = array("daynumber" => 2, "dayname" => ("Sreda"));
//$this->days[3] = array("daynumber" => 3, "dayname" => ("Cetvrtak"));
//$this->days[4] = array("daynumber" => 4, "dayname" => ("Petak"));
//$this->days[5] = array("daynumber" => 5, "dayname" => ("Subota"));
//$this->days[6] = array("daynumber" => 6, "dayname" => ("Nedelja"));
//$this->days array:
//[0] => Array
// (
// [daynumber] => 1
// [dayname] => Monday
// )
//[1] => Array
// (
// [daynumber] => 2
// [dayname] => Tuesday
// )
}
$this->make_blank_start($year, $month);
$this->make_blank_end($year, $month);
} // Close function
function make_blank_start($year, $month) {
/*
Calendar months start on different days
Therefore there are often blank 'unavailable' days at the beginning of the month which are showed as a grey block
The code below creates the blank days at the beginning of the month
*/
// Get first record of the days array which will be the First Day in the month ( eg Wednesday )
$first_day = $this->days[0]['dayname']; $s = 0;
// Loop through $day_order array ( Monday, Tuesday ... )
foreach($this->day_order as $i => $r) {
// Compare the $first_day to the Day Order
if($first_day == $r && $s == 0) {
$s = 1; // Set flag to 1 stop further processing
} elseif($s == 0) {
$blank = array(
"daynumber" => 'blank',
"dayname" => 'blank'
);
// Prepend elements to the beginning of the $day array
array_unshift($this->days, $blank);
}
} // Close foreach
} // Close function
function make_blank_end($year, $month) {
/*
Calendar months start on different days
Therefore there are often blank 'unavailable' days at the end of the month which are showed as a grey block
The code below creates the blank days at the end of the month
*/
// Add blank elements to end of array if required.
$pad_end = 7 - (count($this->days) % 7);
if ($pad_end < 7) {
$blank = array(
"daynumber" => 'blank',
"dayname" => 'blank'
);
for ($i = 1; $i <= $pad_end; $i++) {
array_push($this->days, $blank);
}
} // Close if
$this->calendar_top();
} // Close function
function calendar_top() {
// This function creates the top of the table containg the date and the forward and back arrows
echo "
<div id='lhs'><div id='outer_calendar'>
<table border='0' cellpadding='0' cellspacing='0' id='calendar'>
<tr id='week'>
<td align='left'><a href='?month=" . date("m", $this->back) . "&year=" . date("Y", $this->back) . "'>«</a></td>
<td colspan='5' id='center_date'>" . date("F, Y", $this->selected_date) . "</td>
<td align='right'><a href='?month=" . date("m", $this->forward) . "&year=" . date("Y", $this->forward) . "'>»</a></td>
</tr>
<tr>";
/*
Make the table header with the appropriate day of the week using the $day_format variable as user defined above
Definition:
1: Show First digit, eg: "M"
2: Show First 3 letters, eg: "Mon"
3: Full Day, eg: "Monday"
*/
foreach($this->day_order as $r) {
switch($this->day_format) {
case(1):
echo "<th>" . substr($r, 0, 1) . "</th>";
break;
case(2):
echo "<th>" . substr($r, 0, 3) . "</th>";
break;
case(3):
echo "<th>" . $r . "</th>";
break;
}
// Close switch
} // Close foreach
echo "</tr>";
$this->make_cells();
} // Close function
function make_cells($table = '') {
echo "<tr>";
foreach($this->days as $i => $r) { // Loop through the date array
$j = $i + 1; $tag = 0;
// If the the current day is found in the day_closed array, bookings are not allowed on this day
if(in_array($r['dayname'], $this->day_closed)) {
echo "\r\n<td width='21' valign='top' class='closed'>" . $this->day_closed_text . "</td>";
$tag = 1;
}
// Past days are greyed out
if (mktime(0, 0, 0, $this->month, sprintf("%02s", $r['daynumber']) + 1, $this->year) < strtotime("now") && $tag != 1) {
echo "\r\n<td width='21' valign='top' class='past'>";
// Output day number
if($r['daynumber'] != 'blank') echo $r['daynumber'];
echo "</td>";
$tag = 1;
}
// If the element is set as 'blank', insert blank day
if($r['dayname'] == 'blank' && $tag != 1) {
echo "\r\n<td width='21' valign='top' class='unavailable'></td>";
$tag = 1;
}
// Now check the booking array $this->booking to see whether we have a booking on this day
$current_day = $this->year . '-' . $this->month . '-' . sprintf("%02s", $r['daynumber']);
if(isset($this->bookings_per_day[$current_day]) && $tag == 0) {
$current_day_slots_booked = count($this->bookings_per_day[$current_day]);
if($current_day_slots_booked < $this->slots_per_day) {
echo "\r\n<td width='21' valign='top'>
<a href='calendar.php?month=" . $this->month . "&year=" . $this->year . "&day=" . sprintf("%02s", $r['daynumber']) . "' class='part_booked' title='This day is part booked'>" .
$r['daynumber'] . "</a></td>";
$tag = 1;
} else {
echo "\r\n<td width='21' valign='top'>
<a href='calendar.php?month=" . $this->month . "&year=" . $this->year . "&day=" . sprintf("%02s", $r['daynumber']) . "' class='fully_booked' title='This day is fully booked'>" .
$r['daynumber'] . "</a></td>";
$tag = 1;
} // Close else
} // Close if
if($tag == 0) {
echo "\r\n<td width='21' valign='top'>
<a href='calendar.php?month=" . $this->month . "&year=" . $this->year . "&day=" . sprintf("%02s", $r['daynumber']) . "' class='green' title='Please click to view bookings'>" .
$r['daynumber'] . "</a></td>";
}
// The modulus function below ($j % 7 == 0) adds a <tr> tag to every seventh cell + 1;
if($j % 7 == 0 && $i >1) {
echo "\r\n</tr>\r\n<tr>"; // Use modulus to give us a <tr> after every seven <td> cells
}
}
echo "</tr></table></div><!-- Close outer_calendar DIV -->";
if(isset($_GET['year']))
$this->basket();
echo "</div><!-- Close LHS DIV -->";
// Check booked slots for selected date and only show the booking form if there are available slots
$current_day = $this->year . '-' . $this->month . '-' . $this->day;
$slots_selected_day = 0;
if(isset($this->bookings_per_day[$current_day]))
$slots_selected_day = count($this->bookings_per_day[$current_day]);
if($this->day != 0 && $slots_selected_day < $this->slots_per_day) {
$this->booking_form();
}
} // Close function
function booking_form() {
echo "
<div id='outer_booking'><h2>Available Slots</h2>
<p>
The following slots are available on <span> " . $this->day . "." . $this->month . "." . $this->year . "</span>
</p>
<table width='400' border='0' cellpadding='2' cellspacing='0' id='booking'>
<tr>
<th width='150' align='left'>Start</th>
<th width='150' align='left'>End</th>
<th width='150' align='left'>Price</th>
<th width='20' align='left'>Book</th>
</tr>
<tr>
<td> </td><td> </td><td> </td><td> </td>
</tr>";
// Create $slots array of the booking times
for($i = strtotime($this->booking_start_time); $i<= strtotime($this->booking_end_time); $i = $i + $this->booking_frequency * 60) {
$slots[] = date("H:i:s", $i);
}
// Loop through $this->bookings array and remove any previously booked slots
if($this->is_slot_booked_today == 1) { // $this->is_slot_booked_today created in function 'make_booking_array'
foreach($this->bookings as $i => $b) {
if($b['date'] == $this->year . '-' . $this->month . '-' . $this->day) {
// Remove any booked slots from the $slots array
$slots = array_diff($slots, array($b['start']));
} // Close if
} // Close foreach
} // Close if
// Loop through the $slots array and create the booking table
foreach($slots as $i => $start) {
// Calculate finish time
$finish_time = strtotime($start) + $this->booking_frequency * 60;
echo "
<tr>\r\n
<td>" . $start . "</td>\r\n
<td>" . date("H:i:s", $finish_time) . "</td>\r\n
<td>" . $this->cost_currency_tag . number_format($this->cost_per_slot, 2) . "</td>\r\n
<td width='110'><input data-val='" . $start . " - " . date("H:i:s", $finish_time) . "' class='fields' type='checkbox'></td>
</tr>";
} // Close foreach
echo "</table></div><!-- Close outer_booking DIV -->";
} // Close function
function basket($selected_day = '') {
if(!isset($_GET['day']))
$day = '01';
else
$day = $_GET['day'];
// Validate GET date values
if(checkdate($_GET['month'], $day, $_GET['year']) !== false) {
$selected_day = $_GET['year'] . '-' . $_GET['month'] . '-' . $day;
} else {
echo 'Invalid date!';
exit();
}
echo "<div id='outer_basket'>
<h2>Rezerviši termin za " . $this->day . "." . $this->month . "." . $this->year . "</h2>
<div id='selected_slots'></div>
<div id='basket_details'>
<form method='post' action='book_slots.php'>
<label>Name</label>
<input name='name' id='name' type='text' class='text_box'>
<label>Email</label>
<input name='email' id='email' type='text' class='text_box'>
<label>Phone</label>
<input name='phone' id='phone' type='text' class='text_box'>
<div id='outer_price'>
<div id='currency'>" . $this->cost_currency_tag . "</div>
<div id='total'></div>
</div>
<input type='hidden' name='slots_booked' id='slots_booked'>
<input type='hidden' name='cost_per_slot' id='cost_per_slot' value='" . $this->cost_per_slot . "'>
<input type='hidden' name='booking_date' value='" . $day . '.' . $_GET['month'] . '.' . $_GET['year'] . "'>
<input type='submit' class='classname' value='Make Booking'>
</form>
</div><!-- Close basket_details DIV -->
</div><!-- Close outer_basket DIV -->";
} // Close function
} // Close Class
?>

I want the last few dates of last month and the first few dates of next month to fill up the calendar

echo "<tr>";
for ($i = 1; $i <= $numDays; $i++, $counter++) {
$timeStamp = strtotime("$year-$month-$i");
$thisDay = "$year-$month-$i";
if ($i == 1) {
$firstDay = date("w", $timeStamp);
for ($j = 0; $j < $firstDay; $j++, $counter++) {
//lege ruimte
echo "<td> </td>";
}
}
if ($counter % 7 == 0 && $counter != 0) {
echo"</tr><tr>";
}
$monthstring = $month;
$monthlength = strlen($monthstring);
$daystring = $i;
$daylength = strlen($daystring);
if($monthlength <= 1)
{
$monthstring = "0".$monthstring;
}
if($daylength <= 1){
$daylength = "0".$daystring;
}
?>
<td <?php if ($thisDay == $selectedDate)
{
echo "class='active'";
} else {
echo "class='date'";
}
?> height='75px' <?php if ($thisDay != $selectedDate)
{ echo "onclick='date(" . $daystring . "," . $monthstring . "," . $year . ")'";}
//voorbereiden query
$stmt = $db->prepare("SELECT Omschrijving FROM Event WHERE Startdatum <= ? AND Einddatum >= ?;");
//uitvoeren query
$stmt->execute(array($thisDay, $thisDay));
while ($row = $stmt->fetch())
{
$omschrijving = $row["Omschrijving"];
if ($omschrijving != NULL) {
echo "bgcolor='darkgrey'";
}
}
echo ">" . $i . "<br></td>";
}
echo "</tr>";
?>
</table></div><div class="col-sm-2"></div></div>
</div>
</div>
(this is the complete code that displays the dates and checks if there are events on these dates through the database. the only thing that still needs to be added is the ability to see a few dates before the current selected month and after, primarily to fill up the calendar.)
I currently have a calendar which is laid out following the days of the week (first day is Sunday, last day Monday, then a new row).
I got this to work, but now the problem is that I have an empty space between dates which makes the calendar look incomplete to me.
What I want to do is see the first few dates of next month and the last few dates of last month instead of the blank space, the above code simply counts the blank spaces that need to be there at the beginning of the month.
Is there any way I can rewrite this to display the last dates of the month before? And with that, the first dates of the month after too?

PHP Calendar Issues

I have the following code that I created to generate a Calendar, but it has some issues:
//Labels
$dayLabels = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$monthLables = array("January","February","March","April","May","June","July","August","September","October","November","December");
//max values
$maxDays = 7;
$maxMonths = 12;
//stats
$forceMonth = $_GET['m'];
$forceYear = $_GET['y'];
$todayDate = date("d-m-Y");
$todayDate = date("d-m-Y", strtotime($todayDate));
$explodeToday = explode("-", $todayDate);
$currentDay = $explodeToday[0];
if(isset($forceMonth)) {
$currentMonth = $forceMonth;
} else {
$currentMonth = $explodeToday[1];
};
if(isset($forceYear)) {
$currentYear = $forceYear;
} else {
$currentYear = $explodeToday[2];
};
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
//database values
$startDate = array("01-06-2015","25-06-2015");
$endDate = array("05-06-2015","05-07-2015");
$bookedUser = array("Dexter","James");
//counters
$daysIntoMonth = 0;
$dayCounter = 0;
//debug
echo '<p>Current Month: ' .$monthLables[$currentMonth-1]. ' / ' .$currentMonth. '</p>';
echo '<p>Current Year: ' .$currentYear. '</p>';
//start of Calendar
echo '<table>';
//print days of week
echo '<tr>';
foreach($dayLabels as $day) {
echo '<td style="border-bottom:dashed 1px #DDD;">' .$day. '</td>';
};
echo '</tr>';
while($daysIntoMonth < $daysInMonth) {
//days into month
$daysIntoMonth++;
$temp_inMonth = sprintf("%02d", $daysIntoMonth);
$daysIntoMonth = $temp_inMonth;
//days into week
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
//current calendar date
$calDate = date('d-m-Y', strtotime($daysIntoMonth. '-' .$currentMonth. '-' .$currentYear));
$timeCal = strtotime($calDate);
if($dayCounter == 1) {
echo '<tr>';
};
if($startKey = array_search($calDate, $startDate) !== FALSE) {
$booked = true;
};
if($endKey = array_search($calDate, $endDate) !== FALSE) {
$booked = false;
};
if($booked == true) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else if($booked == true && array_search($calDate, $startDate) !== FALSE) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else if($booked == false && array_search($calDate, $endDate) !== FALSE) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else {
echo '<td>' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
}
if($dayCounter == $maxDays) {
echo '</tr>';
$dayCounter = 0;
};
};
//table is kill
echo '</table>';
The issues I have noticed:
Unable to put a $bookedUser for respective $startDate,$endDate.
When a booking laps over to another month, it skips all the dates until the $endDate.
All Months start on Monday, how would I go about making them start of correct days of the week.
Possible code examples to help me solve my issues would be great, thanks in advance.
Edit:
I have solved problem 3 by using the following code:
$firstDayofMonth = strtotime("01-$currentMonth-$currentYear");
$firstDayofMonth = date("D", $firstDayofMonth);
$firstDayofMonth = array_search($firstDayofMonth, $dayMiniLabels);
$firstDayofMonth = $firstDayofMonth + 1;
$startMonth = 0;
if($firstDayofMonth != 7) {
while($startMonth < $firstDayofMonth) {
echo '<td></td>';
$startMonth++;
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
};
};
For the days and months (problem 3), I would do this:
$todaysNumber = date('w');
$currentDayInText = $dayLabels[$todaysNumber];
And the same for the monhts.
Mostly, in my MySQL-tables, dates are placed like 2015-06-05 and not in European time notation. Maybe that could solve problem 1?

Mysql Dates / PHP

I am working on a calendar in PHP. With the calendar, I am able to query a mysql database and it will show the number of events for each day. The problem I'm having is that it is showing the start and end dates but i need it to also show all the days inbetween.Thus, showing that the days inbetween are also occupied. My current Table has DepDate (departure) AND RetDate (Return Date). Im thinking this has to be done through the mysql query. Any help would be awesome! Thanks buds
<script>
function goLastMonth(month, year, keyname){
if(month == 1) {
--year;
month = 13;
}
--month
var monthstring= ""+month+"";
var monthlength = monthstring.length;
var keyname = "<?php echo $searchTerm; ?>";
if(monthlength <=1){
monthstring = "0" + monthstring;
}
document.location.href ="<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year+"&keyname="+keyname;
}
function goNextMonth(month, year, keyname){
if(month == 12) {
++year;
month = 0;
}
++month
var monthstring= ""+month+"";
var monthlength = monthstring.length;
var keyname = "<?php echo $searchTerm; ?>";
if(monthlength <=1){
monthstring = "0" + monthstring;
}
document.location.href ="<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year+"&keyname="+keyname;
}
</script>
</head>
<?php
if (isset($_GET['day'])){
$day = $_GET['day'];
} else {
$day = date("j");
}
if(isset($_GET['month'])){
$month = $_GET['month'];
} else {
$month = date("n");
}
if(isset($_GET['year'])){
$year = $_GET['year'];
}else{
$year = date("Y");
}
$currentTimeStamp = strtotime( "$year-$month-01");
$monthName = date("F", $currentTimeStamp);
$numDays = date("t", $currentTimeStamp);
$currentTimeStamp = strtotime( "$day-$month-$year"); // added this to reset this value for prev* and next* code
$counter = 0;
?>
<?php
include ('plane.css');
/* ------------------------------------------------------------Calendar Creation---------------------------------------------------------------------- */
include ('planeh.html');
?>
<?php
//get previous month
$prevMonth = $month - 1;
$prevYear = $year;
if($prevMonth <= 0){
$prevMonth = 12;
$prevYear--;
}
$pMonthStr = "" + $prevMonth;
if(strlen($pMonthStr) <= 1)
$pMonthStr = "0" + $pMonthStr;
//get num of day for previous month
$previousTimeStamp = strtotime( "01-$pMonthStr-$prevYear");
$prevNumDays = date("t", $previousTimeStamp);
$numDays = date("t", $currentTimeStamp);
$counter = 0;
for($i = 1; $i < $numDays+1; $i++, $counter++){
$timeStamp = strtotime("$year-$month-$i");
if($i == 1) {
$firstDay = date("w", $timeStamp);
for($j = 0; $j < $firstDay; $j++, $counter++) {
$prevDay = $prevNumDays-$firstDay+$j+1;
echo "<td class = td3><div id = prev>$prevDay</div></td>";
}
}
if($counter % 7 == 0) {
echo"</tr><big></big><tr>";
}
/* Up to this point, everything is the development of the calendar */
$monthstring = $month;
$monthlength = strlen($monthstring);
$daystring = $i;
$daylength = strlen($i);
if($daylength <=0){
$daystring = "0".$daystring;
}
// links and date located on calendar
$todaysDate = date("m/d/y");
/* Indicates date located on calendar */
echo "<td align = center class = td3><div class = button>".$i."</a></div>";
$sqlEvent2 = mysql_query("select * FROM trips where DepDate = '".$year."-".$month."-".$i."'");
$num_rows = mysql_num_rows($sqlEvent2);
if(mysql_errno()){
echo "MySQL error ".mysql_errno().": "
.mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}
echo '<div id="button">';
echo "<a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$i."&year=".$year."&v=true' >".$num_rows."</a></td>";
echo '</div>';
}
echo "<tr>";
echo"</table>";
?>
<div id ="menu">
<?php include ('menu2.php');?>
</ul>
</div>
</div>
</tr>
</body>
</html>
All you need here is to reference the MySQL date and time functions, specifically datediff: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff
An example would be:
SELECT start_dt, end_dt, datediff(end_dt, start_dt) as days_elapsed
FROM my_table
where start_dt and end_dt are both date valued.

Categories