Calendar booking - php

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
?>

Related

How to run multiple queries for a calendar script to make a day unavailable

I have a calendar script that displays up to 6 appointments per morning and per afternoon on any given day. It counts how many are remaining and if all 6 are taken then displays FULL. What I would also like to do is to be able to block out a morning, afternoon, whole day or even whole week (for a holiday for example) and mark them as FULL without having to add 6/12/84 individual rows to the db.
I have tried adding a column called 'block' and setting it's value to 1 for a given day, 0 as default, but I can't get both queries to run at the same time. It then doesn't display the days that still have 6 appointments (i.e. don't have any rows in the db therefore don't have a block value of 0 OR 1). I've tried every which way of nesting 2 while loops and I've tried IF EXISTS in the sql, exists/isset in the PHP but just can't get it to work. Can anyone please help?
date_default_timezone_set('Europe/London');
// 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-d');
$todaynum = date('N');
$hour = date('a');
// Title (Format:August, 2018)
$title = date('F, Y', $timestamp);
// Display Month (Format: August), Display Year (Format: 2018)
$dismth = date(' F ', $timestamp);
$disyr = date('Y', $timestamp);
// Current Year (Format:2018-), Current Month (Format:08-),
$curryr = date('Y-', $timestamp);
$currmth = date('m-', $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++) {
/* create a variable to concantenate the dates into db format */
/*$chosen = $curryr.$currmth.$day;*/
if ($day < 10) {
$date = $ym . '-0' . $day;
}
else {
$date = $ym . '-' . $day;
}
/* find if it's a weekend */
$weekdays = strtotime($date);
$weekday = date('l', $weekdays);
/* create a variable to concantenate the day and dates into display format */
$display = $weekday.', '.$day.$dismth.$disyr;
/* query - count number of appointments for current day and time */
$sqlam = "SELECT count(*) AS amapp FROM wasps_appointments WHERE date = '$date' AND time = 'Morning'";
$resultam = $connection->query($sqlam);
$sqlpm = "SELECT count(*) AS pmapp FROM wasps_appointments WHERE date = '$date' AND time = 'Afternoon'";
$resultpm = $connection->query($sqlpm);
/* start cell - check if today and if yes add class */
if ($today == $date) {
$week .= '<td class="today">';
} else {
$week .= '<td>';
}
/* Write day number into cell */
$week .= '<span class="date">';
$week .= $day;
$week .= '</span>';
/* if weekend show nothing */
if ( $weekday == 'Saturday' || $weekday == 'Sunday' ){ }
/* else (if not weekend) show links */
else {
/* ------------------------ MORNING -----------------------*/
/* display morning appointment availability from query above */
while($row = mysqli_fetch_array($resultam)){
/* if in the future show links */
if ($date >= $today){
/* count how many remaining */
$amremain = 6 - $row['amapp'];
/* change colour according to availability*/
$trafficlight = "green";
if ($amremain == 3 || $amremain == 2) { $trafficlight = "amber";}
elseif ($amremain == 1) { $trafficlight = "red";}
/* check if fully booked */
if ($amremain == 0) {
$week .= 'am <span class="am full">FULL</span><br />';
}
else {
/* write dates into form fields from link */
$week .= 'am <span class="am '.$trafficlight.'">' . $amremain . ' left</span><br />';
}
}
/* else if in the past show nothing */
else { }
}
/* ------------------------ END MORNING -----------------------*/
/* ------------------------ AFTERNOON -----------------------*/
/* display afternoon appointment availability from query above */
while($row = mysqli_fetch_array($resultpm)){
/* if in the future show links */
if ($date >= $today){
$pmremain = 6 - $row['pmapp'];
/* change colour according to availability*/
$trafficlight = "green";
if ($pmremain == 3 || $pmremain == 2) { $trafficlight = "amber";}
elseif ($pmremain == 1) { $trafficlight = "red";}
if ($pmremain == 0) {
$week .= 'pm <span class="pm full">FULL</span>';
}
else {
/* write dates into form fields from link */
$week .= 'pm <span class="pm '.$trafficlight.'">' . $pmremain . ' left</span>';
}
}
/* else if in the past show nothing */
else { }
}
/* ------------------------ END AFTERNOON -----------------------*/
}
/* end cell */
$week .= '</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 = '';
}
}
?>
<div id="calendar">
<div class="datenavigation">< prev <span class="title"><?= $title; ?></span> next ><!-- today--></div>
<div class="key"><span class="am">Morning 8am to 12pm</span><br /><span class="pm">Afternoon 1pm to 6pm</span></div>
<table>
<thead>
<tr>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
<th>S</th>
</tr>
</thead>
<tbody>
<?php
foreach ($weeks as $week) {
echo $week;
}
?>
</tbody>
</table>
</div>

Change language in date()

i have a website with appointments and i use this booking script http://www.planetphp.co.uk/free-php-booking-slots-calendar/.
Unfortunately, i have tried everything to change the language when it shows the month.
class booking_diary {
// Mysqli connection
function __construct($link) {
$this->link = $link;
}
// Settings you can change:
// Time Related Variables
public $booking_start_time = "09:00"; // The time of the first slot in 24 hour H:M format
public $booking_end_time = "21: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 = 3; // 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,$first_name) {
// $day, $month and $year are the $_GET variables in the URL
$this->day = $day;
$this->month = $month;
$this->year = $year;
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->telephone = $telephone;
$this->email = $email;
$this->page_id = $page_id;
$this->user_id = $user_id;
$this->uid = $uid;
$this->pon = $owner;
$this->rsvnumb = $rsvnumb;
// $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(?, '-', ?, '%') and page_id=".$_GET['page_id']."");
$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));
}
/*
Sample output of the $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) . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&telephone=" . $_GET['telephone'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&pon=" . $_GET['pon'] . "&page_id=" . $_GET['page_id'] . "&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) . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&telephone=" . $_GET['telephone'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&pon=" . $_GET['pon'] . "&page_id=" . $_GET['page_id'] . "&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 '<h3>Επέλεξε μία μέρα</h3>';
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='reservation.php?month=" . $this->month . "&year=" . $this->year . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&telephone=" . $_GET['telephone'] . "&pon=" . $_GET['pon'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&page_id=" . $_GET['page_id'] . "&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='reservation.php?month=" . $this->month . "&year=" . $this->year . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&telephone=" . $_GET['telephone'] . "&pon=" . $_GET['pon'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&page_id=" . $_GET['page_id'] . "&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='reservation.php?month=" . $this->month . "&year=" . $this->year . "&first_name=" . $_GET['first_name'] . "&email=" . $_GET['email'] . "&last_name=" . $_GET['last_name'] . "&rsvnumb=" . $_GET['rsvnumb'] . "&telephone=" . $_GET['telephone'] . "&pon=" . $_GET['pon'] . "&user_id=" . $_GET['user_id'] . "&uid=" . $_GET['uid'] . "&page_id=" . $_GET['page_id'] . "&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
Have someone any idea about this script and how can i change the language of the month (greek)?
The date() function can only use English for its outputs. You'd have to use strftime() instead, while setting the locale with setlocale(). This will output in the language of the set locale, in this case - greek.
The two have somewhat different formats, but aren't altogether that different. A brief example is given below.
setlocale(LC_TIME, 'el_GR.UTF-8'); // Set the locale to greek
echo strftime("%A", $d); // Outputs weekname, Monday through Sunday
echo strftime("%m", $this->back) // Outputs month, numerically, e.g. "10"
echo strftime("%B, %Y", $this->selected_date); // Outputs e.g "October, 2016"
// These comments, about the formats, are in English,
// because I don't know the Greek translation
// It will be in Greek should the locale be installed and properly set
Change the date() functions to strftime() instead (with the new parameters, found in the documentation), and you should be good!
If the above doesn't work, it's because that locale (el_GR, for Greek) hasn't been installed on your server.
References
http://php.net/manual/en/function.strftime.php
http://php.net/manual/en/function.setlocale.php
Thank you for your answer. i tried setlocale(LC_TIME, 'el_GR.UTF-8'); but nothing happend. I have tried setlocale(LC_ALL, 'greek'); but the greek words are ???????.When i encode page to windows-1253 i can see the month in greek language but this is not a solution. What can i do?
EDIT:
I found the solution
$date_encoded = strftime('%B %Y', $this->selected_date);
$date_encoded = iconv('Windows-1253', 'UTF-8//IGNORE', $date_encoded);
How we can change the default time to dynamic using mysqli db
// Time Related Variables
public $booking_start_time = "09:00"; // The time of the first slot in 24 hour H:M format
public $booking_end_time = "21:00"; // The time of the last slot in 24 hour H:M format

How to add row values together in a html table (calendar)?

I have a calendar I made with php using an html table.
Each date has an integer value inserted from the database below the day number.
What I want to do is get the sum of each row (week) of the table and put it in the 8th column. How can I do this?
Any help?
<?php
$conn = mysqli_connect('localhost','username','password','database_name');
?>
<html>
<head>
<title>
Calendar
</title>
<link rel="stylesheet" href="/test/style.css">
<script src="/test/script.js"></script>
</head>
<body>
<?php
//This gets today's date
$date = time() ;
//This puts the day, month, and year in seperate variables
$day = date('d', $date) ;
$month = date('m', $date);
$year = date('Y', $date);
//Here we generate the first day of the month
$first_day = mktime(0,0,0,$month, 1, $year) ;
//This gets us the month name
$title = date('F', $first_day) ;
//Here we find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;
switch($day_of_week){
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}
//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;
//Here we start building the table heads
echo "<table border=1 width=294>";
echo "<tr><th colspan=7> $title $year </th></tr>";
echo "<tr><td width=42>S</td><td width=42>M</td><td width=42>T</td>
<td width=42>W</td><td width=42>T</td><td width=42>F</td><td width=42>S</td><td width=42>Total:</td></tr>";
$day_count = 1;
$row_number = 1;
echo "<tr id='row" . $row_number . "'>";
$row_number++;
//first we take care of those blank days
/////////get beginning of month
if($month-1 != 0) {
$last_month = $month-1;
}
else {
$last_month = 12;
}
if($last_month == '12') {
$year = $year-1;
}
$last_month_first_day = mktime(0,0,0,$last_month, 1, $year);
$last_month_days_in_month = cal_days_in_month(0, $last_month, $year);
$last_month_day_of_week = date('D', $last_mont_days_in_month);
$last_month_days_to_add_to_last_month_end = $blank;
$last_month_end = $last_month_days_in_month-$last_month_days_to_add_to_last_month_end;
//end ^^
while ( $blank > 0) {
echo "<td><span style='color:grey'>" . $last_month_end . "</span></td>";
$last_month_end++;
$blank = $blank-1;
$day_count++;
}
//sets the first day of the month to 1
$day_num = 1;
//count up the days, untill we've done all of them in the month
$week_total_mileage = array();
$x = 0;
while ( $day_num <= $days_in_month ) {
//get total miles from database
$getDay = $year . "-" . $month . "-" . $day_num;
$query = "SELECT * FROM table WHERE date='" . $getDay . "'";
$doQuery = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($doQuery)) {
$total_miles = $rows['total_miles'];
}
$num_rows = mysqli_num_rows($doQuery);
echo "<td id='" . $day_count . $row_number . "' value='" . $total_miles . "'
>
<form method='post' action='/test/day.php'>
<input type='hidden' value='" . $day_num . "' name='day'>
<input type='hidden' value='" . $title . "' name='month'>
<input type='hidden' value='" . $year . "' name='year'>
<input type='button' id='dayNum' value='" . $day_num . "'>
</form>
<span id='totalMiless'>Total miles: ";
if($num_rows == 1) {
echo $total_miles;
}
else {
echo '-';
}
echo "</span>
</td>
<div class='hiddenDay' id='" . $day_num . $title . $year . "' style='display:none'>
<span id='totalMiles'>Total miles: ";
if($num_rows == 1) {
echo $total_miles;
}
else {
echo '0';
}
echo "</span></div>";
$week_total_mileage[$day_num] = $total_miles;
$day_num++;
$day_count++;
if ($day_count > 7) {
$total_total = 0;
while($x < 8) {
$total_total = $total_total + $week_total_mileage[$x];
$x++;
}
while($x < 14 && $x > 8) {
$total_total = $total_total + $week_total_mileage[$x];
}
echo "<td>" . $total_total .
"</td></tr><tr id='row" . $row_number . "'>";
empty($week_total_mileage);
$day_count = 1;
$row_number++;
}
}
//Finaly we finish out the table with some blank details if needed
$end_days = 1;
while ( $day_count >1 && $day_count <=7 ) {
echo "<td><span id='endDays'>" . $end_days . "</span></td>";
$day_count++;
$end_days++;
}
echo "</tr></table>";
?>
</body>
</html>
The above code outputs this:
I just went through your script, put all total miles into an array
and calculate sum with
array_sum
Try this code:
<?php
$conn = mysqli_connect('localhost','username','password','database_name');
?>
<html>
<head>
<title>
Calendar
</title>
<link rel="stylesheet" href="/test/style.css">
<script src="/test/script.js"></script>
</head>
<body>
<?php
//This gets today's date
$date = time() ;
//This puts the day, month, and year in seperate variables
$day = date('d', $date) ;
$month = date('m', $date);
$year = date('Y', $date);
//Here we generate the first day of the month
$first_day = mktime(0,0,0,$month, 1, $year) ;
//This gets us the month name
$title = date('F', $first_day) ;
//Here we find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;
switch($day_of_week){
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}
//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;
//Here we start building the table heads
echo "<table border=1 width=294>";
echo "<tr><th colspan=7> $title $year </th></tr>";
echo "<tr><td width=42>S</td><td width=42>M</td><td width=42>T</td>
<td width=42>W</td><td width=42>T</td><td width=42>F</td><td width=42>S</td><td width=42>Total:</td></tr>";
$day_count = 1;
$row_number = 1;
echo "<tr id='row" . $row_number . "'>";
$row_number++;
//first we take care of those blank days
/////////get beginning of month
if($month-1 != 0) {
$last_month = $month-1;
}
else {
$last_month = 12;
}
if($last_month == '12') {
$year = $year-1;
}
$last_month_first_day = mktime(0,0,0,$last_month, 1, $year);
$last_month_days_in_month = cal_days_in_month(0, $last_month, $year);
$last_month_day_of_week = date('D', $last_mont_days_in_month);
$last_month_days_to_add_to_last_month_end = $blank;
$last_month_end = $last_month_days_in_month-$last_month_days_to_add_to_last_month_end;
//end ^^
while ( $blank > 0) {
echo "<td><span style='color:grey'>" . $last_month_end . "</span></td>";
$last_month_end++;
$blank = $blank-1;
$day_count++;
}
//sets the first day of the month to 1
$day_num = 1;
//count up the days, untill we've done all of them in the month
$week_total_mileage = array();
$weekly_total = array();
$x = 0;
while ( $day_num <= $days_in_month ) {
//get total miles from database
$getDay = $year . "-" . $month . "-" . $day_num;
$query = "SELECT * FROM table WHERE date='" . $getDay . "'";
$doQuery = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($doQuery)) {
$total_miles = $rows['total_miles'];
}
$num_rows = mysqli_num_rows($doQuery);
echo "<td id='" . $day_count . $row_number . "' value='" . $total_miles . "'
>
<form method='post' action='/test/day.php'>
<input type='hidden' value='" . $day_num . "' name='day'>
<input type='hidden' value='" . $title . "' name='month'>
<input type='hidden' value='" . $year . "' name='year'>
<input type='button' id='dayNum' value='" . $day_num . "'>
</form>
<span id='totalMiless'>Total miles: ";
if($num_rows == 1) {
echo $total_miles;
}
else {
echo '-';
}
echo "</span>
</td>
<div class='hiddenDay' id='" . $day_num . $title . $year . "' style='display:none'>
<span id='totalMiles'>Total miles: ";
if($num_rows == 1) {
echo $total_miles;
}
else {
echo '0';
}
echo "</span></div>";
if(is_numeric($total_miles)) {
$weekly_total[] = $total_miles;
}
$week_total_mileage[$day_num] = $total_miles;
$day_num++;
$day_count++;
if ($day_count > 7) {
$total_total = 0;
while($x < 8) {
$total_total = $total_total + $week_total_mileage[$x];
$x++;
}
while($x < 14 && $x > 8) {
$total_total = $total_total + $week_total_mileage[$x];
}
echo "<td>" . array_sum($weekly_total) .
"</td></tr><tr id='row" . $row_number . "'>";
empty($week_total_mileage);
$weekly_total = array();
$day_count = 1;
$row_number++;
}
}
//Finaly we finish out the table with some blank details if needed
$end_days = 1;
while ( $day_count >1 && $day_count <=7 ) {
echo "<td><span id='endDays'>" . $end_days . "</span></td>";
$day_count++;
$end_days++;
}
echo "</tr></table>";
?>
</body>
</html>

Separating a date array to have different output for 1st date in array

Basically I am building a calendar/event booking system on my local PC for personal use, I have the functionality working to get the days from my database that have a booking attached to them, and you recolour the dates in the array accordingly, but I'm trying to work out if I could customise the result of the 1st day in each range, and the following days being the same.
Here is how it looks(if it makes it any easier)
And here is the code I am currently using on the page..
<?php
function date_range($first, $last, $step = '+1 day', $output_format = 'Y-m-d' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
?>
<table width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #aaaaaa;">
<?php
$cmonth = date('F');
$cyear = date('Y');
$res = mysql_query("SELECT * FROM trips WHERE year(start_date) = '$cyear' ORDER BY start_date ASC");
$array_days = array();
while ($rows = mysql_fetch_array($res)) {
$selected_dates = date_range(date("Y-m-d",strtotime($rows['start_date'])), date("Y-m-d",strtotime($rows['end_date'])));
foreach($selected_dates as $selected_date){
$array_days[$selected_date]['start_end'] = "". $rows['trip_start'] . " to " . $rows['trip_end'];
$array_days[$selected_date]['colour'] = "". $rows['colour'];
$array_days[$selected_date]['booked'] = "". $rows['booked'];
$array_days[$selected_date]['capacity'] = "". $rows['capacity'];
}
}
?>
<tr>
<td> </td>
<?php for($i=1;$i<=31;$i++){?>
<td class="trip-date-cell"><?php echo $i;?></td>
<?php }?>
</tr>
<?php
$current_month = date("m");
$next_6_month = date("m", strtotime("+5 month", strtotime(date("F") . "1")));
for($i=$current_month;$i<=$next_6_month;$i++){ // 12 months in year
?>
<tr>
<td class="trip-month-cell"><?php echo date('M', mktime(0, 0, 0, $i,10, $cyear)); ?></td>
<?php
$days_in_month = cal_days_in_month(CAL_GREGORIAN,$i,$cyear);
foreach (range(1, $days_in_month) as $days) {
$key = date('Y-m-d', mktime(0, 0, 0, $i, $days, $cyear));
if(array_key_exists($key,$array_days)){
$color = $array_days[$key]['capacity'] - $array_days[$key]['booked'] == 0 ? "#303030" : $array_days[$key]['colour'];
echo "<td class='trip-day-book' style='background-color: ".$color."' alt='".$array_days[$key]['start_end']."' title='".$array_days[$key]['start_end']."'> </td>";
} else {
echo "<td class='trip-day-blank'> </td>";
}
}
?>
</tr>
<?php } ?>
</table>
Any suggestions or advice would be appreciated.
You could store the first date information in your array when reading in the date ranges:
while ($rows = mysql_fetch_array($res)) {
$selected_dates = date_range(date("Y-m-d",strtotime($rows['start_date'])), date("Y-m-d",strtotime($rows['end_date'])));
// default to true: first date is first day in range
$firstDate = true;
foreach($selected_dates as $selected_date) {
// store first day info in array
$array_days[$selected_date]['first_day'] = $firstDate;
// set to false for all following days
if ($firstDate) $firstDate = false;
$array_days[$selected_date]['start_end'] = "". $rows['trip_start'] . " to " . $rows['trip_end'];
$array_days[$selected_date]['colour'] = "". $rows['colour'];
$array_days[$selected_date]['booked'] = "". $rows['booked'];
$array_days[$selected_date]['capacity'] = "". $rows['capacity'];
}
}
and then while rendering access the information to achieve your desired result:
$color = $array_days[$key]['capacity'] - $array_days[$key]['booked'] == 0 ? "#303030" : $array_days[$key]['colour'];
// set content of cell according to first day info
$content = $array_days[$key]['first_day'] ? '<strong>1</strong>' : ' ';
echo "<td class='trip-day-book' style='background-color: ".$color."' alt='".$array_days[$key]['start_end']."' title='".$array_days[$key]['start_end']."'>$content</td>";

Remove passed dates in CodeIgniter Calendar

Is it possible to remove the dates that have already passed (in the past) in Codeigniter Calendar?
I'm using the Calendar Template that was provided in the user's manual
This is possible although I don't know if it is conventional here is my code.
Save to "/application/libraries/MY_Calendar.php"
<?php
class MY_Calendar extends CI_Calendar {
/**
* Generate the calendar
*
* #param int the year
* #param int the month
* #param array the data to be shown in the calendar cells
* #return string
*/
public function generate($year = '', $month = '', $data = array()) {
$local_time = time();
// Set and validate the supplied month/year
if (empty($year)) {
$year = date('Y', $local_time);
} elseif (strlen($year) === 1) {
$year = '200' . $year;
} elseif (strlen($year) === 2) {
$year = '20' . $year;
}
if (empty($month)) {
$month = date('m', $local_time);
} elseif (strlen($month) === 1) {
$month = '0' . $month;
}
$adjusted_date = $this->adjust_date($month, $year);
$month = $adjusted_date['month'];
$year = $adjusted_date['year'];
// Determine the total days in the month
$total_days = $this->get_total_days($month, $year);
// Set the starting day of the week
$start_days = array('sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday' => 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6);
$start_day = isset($start_days[$this->start_day]) ? $start_days[$this->start_day] : 0;
// Set the starting day number
$local_date = mktime(12, 0, 0, $month, 1, $year);
$date = getdate($local_date);
$day = $start_day + 1 - $date['wday'];
while ($day > 1) {
$day -= 7;
}
// Set the current month/year/day
// We use this to determine the "today" date
$cur_year = date('Y', $local_time);
$cur_month = date('m', $local_time);
$cur_day = date('j', $local_time);
$is_current_month = ($cur_year == $year && $cur_month == $month);
// Generate the template data array
$this->parse_template();
// Begin building the calendar output
$out = $this->replacements['table_open'] . "\n\n" . $this->replacements['heading_row_start'] . "\n";
// "previous" month link
if ($this->show_next_prev === TRUE) {
// Add a trailing slash to the URL if needed
$this->next_prev_url = preg_replace('/(.+?)\/*$/', '\\1/', $this->next_prev_url);
$adjusted_date = $this->adjust_date($month - 1, $year);
$out .= str_replace('{previous_url}', $this->next_prev_url . $adjusted_date['year'] . '/' . $adjusted_date['month'], $this->replacements['heading_previous_cell']) . "\n";
}
// Heading containing the month/year
$colspan = ($this->show_next_prev === TRUE) ? 5 : 7;
$this->replacements['heading_title_cell'] = str_replace('{colspan}', $colspan,
str_replace('{heading}', $this->get_month_name($month) . ' ' . $year, $this->replacements['heading_title_cell']));
$out .= $this->replacements['heading_title_cell'] . "\n";
// "next" month link
if ($this->show_next_prev === TRUE) {
$adjusted_date = $this->adjust_date($month + 1, $year);
$out .= str_replace('{next_url}', $this->next_prev_url . $adjusted_date['year'] . '/' . $adjusted_date['month'], $this->replacements['heading_next_cell']);
}
$out .= "\n" . $this->replacements['heading_row_end'] . "\n\n"
// Write the cells containing the days of the week
. $this->replacements['week_row_start'] . "\n";
$day_names = $this->get_day_names();
for ($i = 0; $i < 7; $i++) {
$out .= str_replace('{week_day}', $day_names[($start_day + $i) % 7], $this->replacements['week_day_cell']);
}
$out .= "\n" . $this->replacements['week_row_end'] . "\n";
// Build the main body of the calendar
while ($day <= $total_days) {
$out .= "\n" . $this->replacements['cal_row_start'] . "\n";
for ($i = 0; $i < 7; $i++) {
if ($day > 0 && $day <= $total_days) {
$out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_start_today'] : $this->replacements['cal_cell_start'];
if ($day < date('d')) {
$out .= ' ';
} elseif (isset($data[$day])) {
// Cells with content
$temp = ($is_current_month === TRUE && $day == $cur_day) ?
$this->replacements['cal_cell_content_today'] : $this->replacements['cal_cell_content'];
$out .= str_replace(array('{content}', '{day}'), array($data[$day], $day), $temp);
} else {
// Cells with no content
$temp = ($is_current_month === TRUE && $day == $cur_day) ?
$this->replacements['cal_cell_no_content_today'] : $this->replacements['cal_cell_no_content'];
$out .= str_replace('{day}', $day, $temp);
}
$out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_end_today'] : $this->replacements['cal_cell_end'];
} elseif ($this->show_other_days === TRUE) {
$out .= $this->replacements['cal_cell_start_other'];
if ($day <= 0) {
// Day of previous month
$prev_month = $this->adjust_date($month - 1, $year);
$prev_month_days = $this->get_total_days($prev_month['month'], $prev_month['year']);
$out .= str_replace('{day}', $prev_month_days + $day, $this->replacements['cal_cell_other']);
} else {
// Day of next month
$out .= str_replace('{day}', $day - $total_days, $this->replacements['cal_cell_other']);
}
$out .= $this->replacements['cal_cell_end_other'];
} else {
// Blank cells
$out .= $this->replacements['cal_cell_start'] . $this->replacements['cal_cell_blank'] . $this->replacements['cal_cell_end'];
}
$day++;
}
$out .= "\n" . $this->replacements['cal_row_end'] . "\n";
}
return $out .= "\n" . $this->replacements['table_close'];
}
}
You can see my code diverges from native at line 108 with this snippet:
... if ($day < date('d')) {
$out .= ' ';
} ...
As far as pagination, future months, and past months you will need to modify the snippet as you see fit.
The answer below from William Knauss works out of the box (kudos to you William).
I actually went a little further with it and adapted William's solution to my needs.
Basically I wanted the days in the past to be disabled. As in, I wanted to put a class i the the td element for days in the past and a different class for the elements in the future (including today).
So, the code starting on line 106 looks as follows:
if ($day < date('d')) {
$out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_start_today'] : $this->replacements['cal_cell_start_past'];
}else{
$out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_start_today'] : $this->replacements['cal_cell_start'];
}
if (isset($data[$day])) { // this part was restored to the way it is in the native class.
// Cells with content...
Notice the 'cal_cell_start_past'. This is a new array property in the default_template array in the native class. Starting in line 473.
Now it looks like this:
'cal_row_start' => '<tr>',
'cal_cell_start_past' => '<td class="pastDay">',
'cal_cell_start' => '<td class="day">',
'cal_cell_start_today' => '<td class="day">',
Hope this helps someone else.

Categories