I have php to display the calender and another php to check database to see bookings, If there is a booking on certain day it displays "Booked". In database i have column for date of booking and title. How could i make it to display Title from the database instead of "Booked"?
This is to display calender.
<?php
$monthNames = Array("January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December");
?>
<?php
if (!isset($_REQUEST["month"]))
$_REQUEST["month"] = date("n");
if (!isset($_REQUEST["year"]))
$_REQUEST["year"] = date("Y");
?>
<?php
$cMonth = $_REQUEST["month"];
$cYear = $_REQUEST["year"];
$prev_year = $cYear;
$next_year = $cYear;
$prev_month = $cMonth-1;
$next_month = $cMonth+1;
if ($prev_month == 0 )
{
$prev_month = 12;
$prev_year = $cYear - 1;
}
if ($next_month == 13 )
{
$next_month = 1;
$next_year = $cYear + 1;
}
require("BookingsDB.php");
$myBookingsDB = new BookingsDB();
$bookings = $myBookingsDB->getMonthlyBookings($cMonth,$cYear);
?>
<div align="left">
<table width="400" border="5" align="left" id="calendar">
<tr align="center">
<td bgcolor="#999999" style="color:#FFFFFF"><table width="100%" border="0"
cellspacing="0" cellpadding="0">
<tr>
<td width="50%" align="left"><a href="<?php echo $_SERVER["PHP_SELF"]
. "?month=". $prev_month . "&year=" . $prev_year; ?>"
style="color:#FFFFFF">Previous</a></td>
<td width="50%" align="right"><a href="<?php echo $_SERVER["PHP_SELF"]
. "?month=". $next_month . "&year=" . $next_year; ?>"
style="color:#FFFFFF">Next</a></td>
</tr>
</table></td>
</tr>
<tr>
<td align="center"><table width="100%" border="2" cellpadding="2"
cellspacing="2">
<tr align="center">
<td colspan="7" bgcolor="#999999" style="color:#FFFFFF"><strong> <?php
echo $monthNames[$cMonth-1].' '.$cYear; ?></strong></td>
</tr>
<tr>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>S</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>M</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>T</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>W</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>T</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>F</strong></td>
<td align="center" bgcolor="#999999" style="color:#FFFFFF">
<strong>S</strong></td>
</tr>
<?php
require("connection.php");
$con=mysqli_connect("$mysql_host","$mysql_user","$mysql_password","$mysql_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "select activityEvent.activityTitle from activityEvent";
$result = mysqli_query($con,$sql);
$timestamp = mktime(0,0,0,$cMonth,1,$cYear);
$maxday = date("t",$timestamp);
$thismonth = getdate ($timestamp);
$startday = $thismonth['wday'];
$today = getdate();
for ($i=0; $i<($maxday+$startday); $i++)
{
if(($i % 7) == 0 )
{
echo "<tr> ";
}
if($i < $startday)
{
echo "<td></td> ";
}
else
{
$day = $i - $startday + 1;
$thisDate = new DateTime("$cYear-$cMonth-$day");
$jsEvent[] = "document.getElementById('trigger" . $i . "').onclick = function() {showForm()};";
echo "<td align='center' valign='middle' height='20px'><a href='#' id='trigger" . $i . "'>". ($i - $startday + 1) . "</a>";
foreach ($bookings as $bookingDate)
{
if ($thisDate==$bookingDate)
{
echo "Booked";
while($row = mysqli_fetch_array($result))
{
echo $sql= "select activityEvent.activityTitle from activityEvent";
}
}
}
echo "</td>";
}
if(($i % 7) == 6 )
{
echo "</tr> ";
}
}
mysqli_close($con);
?>
<script type="text/javascript">
<?php foreach($jsEvent as $event)
{
echo $event;
}
?>
function showForm(){
document.getElementById('timeslots').style.display="block";
};
</script>
</table></td>
</tr>
</table>
This PHP checks booked dates in the database.
<?php
class BookingsDB
{
private $bookings = array();
private $con;
public function BookingsDB()
{
require("connection.php");
$this->con = mysqli_connect($mysql_host,$mysql_user,$mysql_password,$mysql_database);
}
public function getMonthlyBookings($thisMonth,$thisYear)
{
$sql = "SELECT date,activityTitle FROM activityEvent WHERE YEAR(date) = $thisYear AND MONTH(date) = $thisMonth";
$result = mysqli_query($this->con,$sql);
while($row=mysqli_fetch_array($result))
{
$thisBooking = $row['date'];
$thisBookingDateTime = new DateTime($thisBooking);
array_push($this->bookings,$thisBookingDateTime);
}
return $this->bookings;
}
public function close()
{
mysqli_close($this->con);
}
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.red
{
color: red
}
.green
{
background-color: aquamarine;
}
table
{
text-align: center;
}
td
{
height: 60px;
width: 100px;
}
.opcity
{
background-color: rgba(0,0,0,.2);
}
</style>
</head>
<body>
<?php
$Cur_day = date('d');
$Cur_Month = date('m');
$Cur_Year = date('Y');
$op = '';
if (isset($_REQUEST['month']) || isset($_REQUEST['year']) && isset($_REQUEST['stday']))
{
$Mo = $_REQUEST['month'];
$Year = $_REQUEST['year'];
$query_date = $Year . '-' . $Mo . '-21';
if (isset($_REQUEST['opra']))
{
$str = $_REQUEST['opra'];
if ($str == 'iny')
{
$op = '+1 year';
}
if ($str == 'dey')
{
$op = '-1 year';
}
if ($str == 'inm')
{
$op = '+1 month';
}
if ($str == 'dem')
{
$op = '-1 month';
}
if ($str == 'dem' || $str == 'inm' || $str == 'dey' || $str == 'iny')
{
$query_date1 = date('Y-m-01', strtotime($op, strtotime($query_date)));
$lastDay = date('t', strtotime($op, strtotime($query_date)));
$year = date('Y', strtotime($op, strtotime($query_date)));
$month = date('n', strtotime($op, strtotime($query_date)));
$Month_Name = date('M', strtotime($op, strtotime($query_date)));
$pre_month = date('t', strtotime('-1 month', strtotime($year . '-' . $month . '-21')));
}
if ($str == 'No')
{
$query_date1 = date('Y-m-01', strtotime($query_date));
$lastDay = date('t', strtotime($query_date));
$year = date('Y', strtotime($query_date));
$month = date('n', strtotime($query_date));
$Month_Name = date('M', strtotime($query_date));
$pre_month = date('t', strtotime('-1 month', strtotime($year . '-' . $month . '-21')));
}
}
?>
<input type="hidden" name="txt_year" id="txt_year1" value="<?php echo $year; ?>">
<input type="hidden" name="txt_month1" id="txt_month1" value="<?php echo $month; ?>">
<table border="1">
<tr>
<td><<</td>
<td><</td>
<td colspan="3"><?php echo $Month_Name . "-" . $year; ?></td>
<td>></td>
<td>>></td>
</tr>
<tr>
<?php
echo '<tr>';
for ($i = 1; $i <= 7; $i++)
{
if ($_REQUEST['stday'] == 'Sun')
{
$j_val = 0;
echo "<th>" . date("l", gmmktime(0, 0, 0, 11, $i, 2015));
echo '</th>';
} else
{
$j_val = 1;
echo "<th>" . date("l", gmmktime(0, 0, 0, 6, $i, 2015));
echo '</th>';
}
}
echo '</tr>';
?>
</tr>
<?php
$Conn = new mysqli("localhost", "root", "", "demo");
$firstDays = mktime(0, 0, 0, date($month), 1, date($year));
$weekday = date('N', $firstDays);
$i = 0;
$j = 0;
$date = 1;
$Count = 0;
$Count1 = 0;
$next_mo = 1;
function Holiday($day1, $month1, $year1)
{
global $Conn;
$result = $Conn->query("SELECT * FROM holiday");
while ($row = mysqli_fetch_assoc($result))
{
if ($row['day'] == $day1 && $row['month'] == $month1 && $row['year'] == $year1)
{
return $row['title'] . "<br>";
}
}
}
for ($i = 0; $i < 6; $i++)
{
echo '<tr>';
$pre_month = $pre_month - ($weekday - $j_val);
for ($j = $j_val; $j <= 6 + $j_val; $j++)
{
if ($Count < $weekday - $j_val && ($weekday != 7 || $_REQUEST['stday'] == 'Mon'))
{
echo "<td class='opcity'>" . ( ++$pre_month) . "</td>";
$Count++;
} else
{
if ($date <= $lastDay)
{
if ($Cur_day == $date && $Cur_Month == $month && $Cur_Year == $year)
{
if (date("l", gmmktime(0, 0, 0, $month, $date, $year)) == 'Sunday')
{
echo '<td class = "green red">';
echo Holiday($date, $month, $year);
} else
{
echo '<td class = "green">';
echo Holiday($date, $month, $year);
}
} else
{
if (date("l", gmmktime(0, 0, 0, $month, $date, $year)) == 'Sunday')
{
echo '<td class = "red">';
echo Holiday($date, $month, $year);
} else
{
echo '<td >';
echo Holiday($date, $month, $year);
}
}
echo $date;
echo '</td>';
$date++;
if ($date == $lastDay)
{
$i = 7;
}
} else
{
echo "<td class='opcity'>" . $next_mo++ . "</td>";
}
}
}
echo '</tr>';
}
}
?>
</table>
</body>
</html>
//<Ajax_cal.php
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="JS/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
function Caleonload()
{
$('#month').val('<?php echo date("n"); ?>');
$('#year').val('<?php echo date('Y'); ?>');
Opretion('No');
}
function Cal(month)
{
$('#month').val(month);
Opretion('No');
}
function Cal1(year)
{
$('#year').val(year);
Opretion('No');
}
function Opretion(Op)
{
var st_day = $('input[type="radio"][class="rd_sun_mon"]:checked').val();
var Mo = $('#month').val();
var Year = $('#year').val();
var Op1 = Op;
$.post("AJAX/Ajax_Cal.php",
{
month: Mo,
year: Year,
opra: Op1,
stday: st_day
},
function (data)
{
$('#Show_Cal').html(data);
var txt_year = $('#txt_year1').val();
$("#year").html('');
for (var y = parseInt(txt_year) - 5; y < parseInt(txt_year) + 5; y++)
{
$("#year").append('<option value="' + y + '">' + y + '</option>');
}
$('#year').val(txt_year);
$('#month').val($('#txt_month1').val());
}
);
}
function incyear()
{
Opretion('iny');
}
function deyear()
{
Opretion('dey');
}
function incmonth()
{
Opretion('inm');
}
function demonth()
{
Opretion('dem');
}
</script>
</head>
<body onload="Caleonload()">
<select name="month" id="month" onchange="Cal(this.value)" size="1">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="year" id="year" onchange="Cal1(this.value)" size="1">
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
Starting Day :
<input type="radio" name="rd_sun_mon" class="rd_sun_mon" value="Sun" checked="" onchange="Opretion('No')">Sunday
<input type="radio" name="rd_sun_mon" class="rd_sun_mon" value="Mon" onchange="Opretion('No')">Monday
<div id="Show_Cal"></div>
</body>
</html>
DATA BASE PHP MY ADDMIN:
CREATE TABLE IF NOT EXISTS holiday (
id int(5) NOT NULL AUTO_INCREMENT,
day int(4) NOT NULL,
month int(4) NOT NULL,
year int(6) NOT NULL,
title varchar(20) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
I think your problem is that is that you need to put the format in order to compare two Datetime :
if ($thisDate->format('Y-m-d')==$bookingDate->format('Y-m-d'))
{
echo "Booked";
....
}
In addition to #SimonGuichard's answer, I suggest that you return an associative array from the getMonthlyBookings function that contains both the date and the activityTitle. This way, you wouldn't have to select the title from the database again when it needs to be displayed.
public function getMonthlyBookings($thisMonth,$thisYear) {
$sql = "SELECT date,activityTitle FROM activityEvent WHERE YEAR(date) = $thisYear AND MONTH(date) = $thisMonth";
$result = mysqli_query($this->con,$sql);
while($row=mysqli_fetch_array($result)) {
$this->bookings[] = array('date'=>new DateTime($row['date']), 'activityTitle'=>$row['activityTitle']);
}
return $this->bookings;
}
Then in the script that displays the calendar, you should modify it this way:
$day = $i - $startday + 1;
$thisDate = new DateTime("$cYear-$cMonth-$day");
$jsEvent[] = "document.getElementById('trigger" . $i . "').onclick = function() {showForm()};";
echo "<td align='center' valign='middle' height='20px'><a href='#' id='trigger" . $i . "'>". ($i - $startday + 1) . "</a>";
// $bookings is an associative array of the form array('0'=>array('date'=>'date_value', 'activityTitle'=>'activityTitle_value'))
foreach ($bookings as $key => $value) {
if ($thisDate->format('Y-m-d') === $value['date']->format('Y-m-d')) {
// this prints out the activity title
echo $value['activityTitle'];
}
}
Related
Hii i am working on portal which requires calendar from custom dates like from 14 Jul to 14 Aug.I have made a demo which starts properly i.e.if 14th july starts from Thursday but not ending at sunday which is on 14 aug. Take a look what i have done
function getCalender($year = '',$month = '')
{
$startDate = "2016-07-03";
$endDate = "2016-07-31";
$dateYear = ($year != '')?$year:date("Y");
$dateMonth = ($month != '')?$month:date("m");
$date = $dateYear.'-'.$dateMonth.'-01';
$currentMonthFirstDay = date("N",strtotime($date));
$startDateFrom = date("N",strtotime($startDate));
$endDateFrom = date("N",strtotime($endDate));
$timestamp = strtotime($startDate);
$dayCount = date("d", $timestamp);
$timestamp1 = strtotime($endDate);
$dayCountend = date("d", $timestamp1);
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
//$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
//$boxDisplay = 29
?>
<div id="calender_section">
<h2>
<!--<<-->
<select name="month_dropdown" class="month_dropdown dropdown"><?php echo getAllMonths($dateMonth); ?></select>
<select name="year_dropdown" class="year_dropdown dropdown"><?php echo getYearList($dateYear); ?></select>
<!-->>-->
</h2>
<div id="event_list" class="none"></div>
<!--For Add Event-->
<div id="event_add" class="none">
<p>Add Event on <span id="eventDateView"></span></p>
<p><b>Event Title: </b><input type="text" id="eventTitle" value=""/></p>
<input type="hidden" id="eventDate" value=""/>
<input type="button" id="addEventBtn" value="Add"/>
</div>
<div id="calender_section_top">
<ul>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
<li>Sun</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
for($cb=1;$cb<=$dayCountend;$cb++){
//echo $cb;
if(($cb >= $startDateFrom) && $cb<=$dayCountend)
{
/*if(($cb >= $currentMonthFirstDay+1 || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay)){*/
//Current date
$currentDate = $dateYear.'-'.$dateMonth.'-'.$dayCount;
$currentdate = date("D M j",strtotime($currentDate));
$eventNum = 0;
//Include db configuration file
include 'dbConfig.php';
//Get number of events based on the current date
$result = $db->query("SELECT title FROM events WHERE date = '".$currentDate."' AND status = 1");
$eventNum = $result->num_rows;
//Define date cell color
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
echo '<li date="'.$currentDate.'" class="grey date_cell">';
}elseif($eventNum > 0){
echo '<li date="'.$currentDate.'" class="light_sky date_cell">';
}else{
echo '<li date="'.$currentDate.'" class="date_cell">';
}
//Date cell
echo '<span>';
echo $cb;
echo '</span>';
//Hover event popup
/*echo '<div id="date_popup_'.$currentDate.'" class="date_popup_wrap none">';
echo '<div class="date_window">';
echo '<div class="popup_event">Events ('.$eventNum.')</div>';
echo ($eventNum > 0)?'view events<br/>':'';
//For Add Event
echo 'add event';
echo '</div></div>';
echo '</li>';*/
$dayCount++;
?>
<?php }else{ ?>
<li><span> </span></li>
<?php } } ?>
</ul>
</div>
</div>
<?php
}
?>
I tried for your code and i found one logic i took start date and end date from the user and made the array of the dates which are present between two.
Then calendar should start from for ex. 3 Jul 2016 the day is Sunday for that i inserted - upto first date. Check below what i have done
function getCalender($year = '',$month = '',$startDate = '',$endDate = '')
{
$finalArray = array();
$startDate = "2016-07-03";
$endDate = "2016-08-31";
$date1 = createDateRangeArray('2016-07-03 ','2016-08-31');
//$date = $dateYear.'-'.$dateMonth.'-01';
$startDateFrom = date("N",strtotime($startDate));
$endDateFrom = date("N",strtotime($endDate));
//Take the day from the date
$timestamp = strtotime($startDate);
$dayCount = date("d", $timestamp);
//Take the month from the date
$timestampend = strtotime($endDate);
$dayCountend = date("d", $timestampend);
//Take the month from the date
$timestampmonth = strtotime($startDate);
$monthstart = date("m", $timestampmonth);
//Take the month from the date
$timestampmonthend = strtotime($endDate);
$monthend = date("m", $timestampmonthend);
//Take the year from the start date
$yearstart = strtotime($startDate);
$yearofStart = date("y", $yearstart);
//Take the year from the end date
$yearend = strtotime($endDate);
$yearofEnd = date("y", $yearend);
//cal difference between start date and month
$differenceStartDate = $dayCount - 1;
//cal difference between end date and month
$totalDaysOfMonthEnd = cal_days_in_month(CAL_GREGORIAN,$monthend,$yearofEnd);
$totalDaysOfMonthStart = cal_days_in_month(CAL_GREGORIAN,$monthstart,$yearofEnd);
if($monthstart == $monthend)
{
echo "Show one month calendar";
}
else
{
$diffmonth = $monthend-$monthstart;
}
$differenceStartDate = $dayCountend - $totalDaysOfMonth;
for($i=1;$i<$startDateFrom;$i++)
{
$date[] = '-';
}
array_push($date,$date1);
for($j=0;$j<count($date);$j++)
{
if(strlen($date[$j])==1)
{
array_push($finalArray,$date[$j]);
}
else
{
for($k=0;$k<count($date[$j]);$k++)
{
array_push($finalArray,$date[$j][$k]);
}
}
}
print_r($finalArray);
$timestamp1 = strtotime($endDate);
$dayCountend = date("d", $timestamp1);
$now = strtotime($startDate);
$your_date = strtotime($endDate);
$datediff = $your_date - $now;
$diff= floor($datediff/(60*60*24));
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
//$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
$boxDisplay = $diff;
?>
<div id="calender_section">
<h2>
<!--<<-->
<!-- <select name="month_dropdown" class="month_dropdown dropdown"><?php echo getAllMonths($dateMonth); ?></select>
<select name="year_dropdown" class="year_dropdown dropdown"><?php echo getYearList($dateYear); ?></select>-->
<!-->>-->
</h2>
<div id="event_list" class="none"></div>
<!--For Add Event-->
<div id="event_add" class="none">
<p>Add Event on <span id="eventDateView"></span></p>
<p><b>Event Title: </b><input type="text" id="eventTitle" value=""/></p>
<input type="hidden" id="eventDate" value=""/>
<input type="button" id="addEventBtn" value="Add"/>
</div>
<div id="calender_section_top">
<ul>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
<li>Sun</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
for($cb=0;$cb<count($finalArray);$cb++)
{
//echo $cb;
$date = $finalArray[$cb];
$month = strtotime($date);
$month = date("m", $month);
if(($cb >= $startDateFrom -1))
{
/*if(($cb >= $currentMonthFirstDay+1 || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay)){*/
//Current date
$currentDate = $finalArray[$cb];
//$currentdate = date("D M j",strtotime($currentDate));
$eventNum = 0;
//Include db configuration file
//Define date cell color
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
echo '<li date="'.$currentDate.'" class="grey date_cell">';
echo '<select name="select"></select>
<option value="0"></option>';
}elseif($eventNum > 0){
echo '<li date="'.$currentDate.'" class="light_sky date_cell">';
echo '<select name="select"></select>
<option value="0"></option>';
}else{
echo '<li date="'.$currentDate.'" class="date_cell">';
echo '<select name="select"></select>
<option value="0"></option>';
}
//Date cell
echo '<span>';
echo $currentDate;
echo '</span>';
$dayCount++;
?>
<?php }else{ ?>
<li><span> </span></li>
<?php } } ?>
</ul>
</div>
</div>
<?php
}
function createDateRangeArray($strDateFrom,$strDateTo)
{
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
?>
Take a look at a code and you will understand that easily
The answer given by #BeDeveloper is fine.I made something like below which automatically disable all the other dates for ex.if date 3 it will disable 1 and 2
<style>
/* calendar */
h1 { font-family: calibri; font-size: 20px; color: #6d6d6d}
table.calendar { border-left:1px solid #999; }
tr.calendar-row { }
td.calendar-day { min-height:80px; font-size:11px; position:relative; } * html div.calendar-day { height:80px; }
td.calendar-day:hover { background:#eceff5; }
td.calendar-day-np { background:#eee; min-height:80px; } * html div.calendar-day-np { height:80px; }
td.calendar-day-head { background:#ccc; font-weight:bold; text-align:center; width:120px; padding:5px; border-bottom:1px solid #999; border-top:1px solid #999; border-right:1px solid #999; }
div.day-number { background:#999; padding:5px; color:#fff; font-weight:bold; float:right; margin:-5px -5px 0 0; width:20px; text-align:center; }
/* shared */
td.calendar-day, td.calendar-day-np { width:120px; padding:5px; border-bottom:1px solid #999; border-right:1px solid #999; }
</style>
<?php
/* draws a calendar */
function draw_calendar($month,$year,$startDate,$endDate){
$startDate = date('Y-m-d',$startDate);
$endDate = date('Y-m-d',$endDate);
$timestamp = strtotime($startDate);
$dayCountstart = date("d", $timestamp);
$timestamp = strtotime($endDate);
$dayCountend = date("d", $timestamp);
$timestampmonth = strtotime($startDate);
$monthstart = date("m", $timestampmonth);
$timestampmonthend = strtotime($endDate);
$monthend = date("m", $timestampmonthend);
$yearend = strtotime($endDate);
$yearofEnd = date("y", $yearend);
$dayMinus = $dayCountstart - 01;
$totalDaysOfMonthEnd = cal_days_in_month(CAL_GREGORIAN,$monthend,$yearofEnd);
$dayEndMinus = $totalDaysOfMonthEnd - $dayCountend;
/* draw table */
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
/* table headings */
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
/* days and weeks vars now ... */
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
/* row for week one */
$calendar.= '<tr class="calendar-row">';
/* print "blank" days until the first of the current week */
for($x = 0; $x < $running_day; $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
$days_in_this_week++;
endfor;
/* keep going with days.... */
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
$calendar.= '<td class="calendar-day">';
/* add in the day number */
if($monthstart == $month)
{
if($list_day <= $dayMinus)
{
$calendar.= '<div class="day-number123">'.$list_day.'</div>';
}
else
{
$calendar.= '<div class="day-number">'.$list_day.'</div>';
}
}
else
{
if($monthend == $month)
{
if($list_day <= $dayCountend)
{
$calendar.= '<div class="day-number">'.$list_day.'</div>';
}
else
{
$calendar.= '<div class="day-number123">'.$list_day.'</div>';
}
}
else
{
$calendar.= '<div class="day-number">'.$list_day.'</div>';
}
}
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$calendar.= str_repeat('<p> </p>',2);
$calendar.= '</td>';
if($running_day == 6):
$calendar.= '</tr>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<tr class="calendar-row">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
/* finish the rest of the days in the week */
/* if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
endfor;
endif;*/
/* final row */
$calendar.= '</tr>';
/* end the table */
$calendar.= '</table>';
/* all done, return result */
return $calendar;
}
/* sample usages */
/*echo '<h2>July 2009</h2>';
echo draw_calendar(7,2009);
echo '<h2>August 2009</h2>';
echo draw_calendar(8,2009);
*/
$start = $startDate= $month = strtotime('2016-02-02');
$end = $endDate = strtotime('2016-03-03');
while($month < $end)
{
//$a = date('m Y', $month), PHP_EOL;
$startDate = $start;
$endDate = $end;
$newMonthInRange = date('m', $month);
$newYearInRange = date('Y', $month);
$newMonthInRangeTitle = date('F Y', $month);
$month = strtotime("+1 month", $month);
echo "<h1>".$newMonthInRangeTitle."</h1>";
echo draw_calendar($newMonthInRange,$newYearInRange,$startDate,$endDate);
}
?>
I am trying to create a PHP/MySQL event calendar. However it doesn't go quite right. Below is my code:
// calender.php
$servername = "localhost";
$username = "username";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
#mysqli_select_db("calen");
if (!#mysqli_select_db) {
die("database connection failed".mysqli_connect_error());
}
/*
mysqli_connect($hostname,$username,$password) or die ($error);
mysqli_select_db($dbname) or die ($error);
*/
?>
<html>
<head>
<script>
function lastmonth(month,year) {
if (month == 1) {
--year;
month = 13;
}
--month
var monthstring= ""+month+"";
var monthlength = monthstring.length;
if (monthlength <=1) {
monthstring = "0" + monthstring;
}
document.location.href = "<?= $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
function nextmonth(month,year) {
if(month == 12) {
++year;
month = 0;
}
++month
var monthstring= ""+month+"";
var monthlength = monthstring.length;
if (monthlength <=1) {
monthstring = "0" + monthstring;
}
document.location.href = "<?=$_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
</script>
</head>
<body>
<?php
if (isset($_GET['day'])) { //to pass variable
$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-$day");
$monthname = date("F", $currentTimeStamp);
$numofdays = date("t", $currentTimeStamp);
$counter = 0;
?>
<?php
if (isset($_GET['add'])) {
$title =$_POST['txttitle'];
$detail =$_POST['txtdetail'];
$eventdate = $month."/".$day."/".$year;
$insert = "INSERT into calendar(Title,Detail,EventDate,DateAdded) values ('".$title."','".$detail."','".$eventdate."',now())";
$check = mysqli_query($conn,$insert);
if ($check ) {
echo "Event Added...";
} else {
echo "Failed....";
}
}
?>
<table border='1'>
<tr>
<td><input style='width:50px;' type='button' value='<' name='previous' onclick="lastmonth(<?php echo $month.",".$year ?>)"> </td>
<td colspan='5' align='center'> <?php echo $monthname.",".$year ?> </td>
<td><input style='width:50px;' type='button' value='>' name='next' onclick="nextmonth(<?php echo $month.",".$year ?>)"></td>
</tr>
<tr>
<td width='50px' align='center'>Sun</td>
<td width='50px'align='center'>Mon</td>
<td width='50px'align='center'>Tue</td>
<td width='50px'align='center'>Wed</td>
<td width='50px'align='center'>Thu</td>
<td width='50px'align='center'>Fri</td>
<td width='50px'align='center'>Sat</td>
</tr>
<?php
echo "<tr>";
for ($i=1;$i<$numofdays+1;$i++,$counter++) {
$TimeStamp = strtotime("$year-$month-$i");
if ($i == 1) {
$firstday = date("w", $TimeStamp); //which day 1 falls on
for ($j = 0; $j < $firstday; $j++, $counter++) {
echo "<td> </td>";
}
}
if ($counter % 7 == 0) {
echo "</tr><tr>";
}
$monthstring=$month;
$monthlength=strlen($monthstring);
$daystring=$i;
$daylength=strlen($daystring);
if ($monthlength<=1) {
$monthstring = "0".$monthstring;
}
if ($daylength<=1) {
$daystring="0".$daystring;
}
echo "<td align='center'> <a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year."&v=true'>".$i."</a> </td>";
}
echo "</tr>";
?>
</table>
<?php
if (isset($_GET['v'])) {
echo "<a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year."&v=true&f=true'>Add Event </a>";
if (isset($_GET['f'])) {
include("event.php");
}
}
?>
</body>
</html>
event.php
<form name='event' method='POST' action="<?php $_SERVER['PHP_SELF']; ?>?month=<?php echo $month;?>&day=<?php echo $day;?>&year=<?php echo $year; ?>&v=true&add=true">
<table width='400px' border='0'>
<tr>
<td width='150px'>Title</td>
<td width='250px'><input type='text' name='txttitle'</td>
</tr>
<tr>
<td width='150px'>Detail</td>
<td width='250px'><textarea name='txtdetail'></textarea></td>
</tr>
<tr>
<td colspan='2' align='center'><input type='submit' name='btnadd' value='Add Event'></td>
</tr>
</table>
</form>
SQL:
CREATE TABLE `calendar` (
`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`Title` VARCHAR( 65 ) NOT NULL ,
`Detail` VARCHAR( 255 ) NOT NULL ,
`EventDate` VARCHAR( 10 ) NOT NULL ,
`DateAdded` DATE NOT NULL
);
I am unable to insert data into the database. I have pasted my calendar.php, event.php and SQL code. Kindly please check the code and help me out in inserting the data.
You need to add the connection variable with the mysqli_select_db(). So your code will be:
<?php
$servername = "localhost";
$username = "username";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//#mysqli_select_db($conn, "calen");
if(!mysqli_select_db($conn, "calen")) {
die ("database connection failed".mysqli_connect_error());
}
/*
mysqli_connect($hostname,$username,$password) or die ($error);
mysqli_select_db($dbname) or die ($error);
*/
?>
<html>
<head>
<script>
function lastmonth(month,year)
{
if(month == 1)
{
--year;
month = 13;
}
--month
var monthstring= ""+month+"";
var monthlength = monthstring.length;
if(monthlength <=1)
{
monthstring = "0" + monthstring;
}
document.location.href ="<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
function nextmonth(month,year)
{
if (month == 12) {
++year;
month = 0;
}
++month
var monthstring= ""+month+"";
var monthlength = monthstring.length;
if (monthlength <=1) {
monthstring = "0" + monthstring;
}
document.location.href ="<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
</script>
</head>
<body>
<?php
if (isset($_GET['day'])) { //to pass variable
$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-$day");
$monthname = date("F", $currentTimeStamp);
$numofdays = date("t", $currentTimeStamp);
$counter = 0;
?>
<?php
if (isset($_GET['add'])) {
$title =$_POST['txttitle'];
$detail =$_POST['txtdetail'];
$eventdate = $month."/".$day."/".$year;
$insert = "INSERT INTO calendar (Title,Detail,EventDate,DateAdded) VALUES ('".$title."','".$detail."','".$eventdate."', NOW())";
$check = mysqli_query($conn,$insert);
if ($check) {
echo "Event Added...";
} else {
echo "Failed....";
}
}
?>
<table border='1'>
<tr>
<td> <input style='width:50px;' type='button' value='<' name='previous' onclick="lastmonth(<?php echo $month.",".$year ?>)"> </td>
<td colspan='5' align='center'> <?php echo $monthname.",".$year ?> </td>
<td><input style='width:50px;' type='button' value='>' name='next' onclick="nextmonth(<?php echo $month.",".$year ?>)"></td>
</tr>
<tr>
<td width='50px' align='center'>Sun</td>
<td width='50px'align='center'>Mon</td>
<td width='50px'align='center'>Tue</td>
<td width='50px'align='center'>Wed</td>
<td width='50px'align='center'>Thu</td>
<td width='50px'align='center'>Fri</td>
<td width='50px'align='center'>Sat</td>
</tr>
<?php
echo "<tr>";
for ($i=1;$i<$numofdays+1;$i++,$counter++) {
$TimeStamp = strtotime("$year-$month-$i");
if ($i == 1) {
$firstday = date("w", $TimeStamp); //which day 1 falls on
for ($j = 0; $j < $firstday; $j++, $counter++) {
echo "<td> </td>";
}
}
if($counter % 7 == 0) {
echo "</tr><tr>";
}
$monthstring=$month;
$monthlength=strlen($monthstring);
$daystring=$i;
$daylength=strlen($daystring);
if ($monthlength<=1) {
$monthstring = "0".$monthstring;
}
if ($daylength<=1) {
$daystring="0".$daystring;
}
echo "<td align='center'> <a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year."&v=true'>".$i."</a> </td>";
}
echo "</tr>";
?>
</table>
<?php if (isset($_GET['v'])) {
echo "<a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year."&v=true&f=true'>Add Event </a>";
if (isset($_GET['f'])) {
include("event.php");
}
}
?>
</body>
</html>
Hope this works for you!
More information at http://www.w3schools.com/php/func_mysqli_select_db.asp
I am creating an events calendar for my website and I have used this tutorial and this other one, as well as the youtube tutorial by unknown ghost.
However, when I enter an event, it comes up as successful but doesn't turn blue.
Have I made an error/typo that could explain why it isn't turning blue?
Also once an event has been added, it does display at the bottom but if I refresh the page the event gets added again automatically.
Went through each month and realised February doesn't come up. Why is this?
Here is my code:
calendar.php
<?php
include("functions.php")
?>
<html>
<head>
<title>Event Calendar</title>
<script>
function goLastMonth(month, year){
if(month == 1) {
--year;
month = 13;
}
--month
var monthstring = ""+month+"";
var monthlength = monthstring.length;
if(monthlength <=1){
monthstring = "0"+monthstring;
}
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
function goNextMonth(month, year){
if(month == 12) {
++year;
month = 0;
}
++month
var monthstring = ""+month+"";
var monthlength = monthstring.length;
if(monthlength <=1){
monthstring = "0"+monthstring;
}
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
</script>
<style>
.today{
background-color: #00ff00;
}
.event{
background-color: #0000ff;
}
</style>
</head>
<body>
<?php
//get current date or specific month and year
if (isset($_GET['day'])){
$day = $_GET['day'];
} else {
$day = date("d");
}
if(isset($_GET['month'])){
$month = $_GET['month'];
} else {
$month = date("m");
}
if(isset($_GET['year'])){
$year = $_GET['year'];
}else{
$year = date("Y");
}
//get date data for display such as month name
$currentTimeStamp = strtotime( "$day-$month-$year");
$monthName = date("F", $currentTimeStamp);
//get the number of days in the current month and year
$numDays = date("t", $currentTimeStamp);
//keep track of the number of cell created
$counter = 0;
?>
<?php
if(isset($_GET['add'])) {
$name = $_POST['Event_Name'];
$details = $_POST['Details'];
$date = $day."/".$month."/".$year;
$location = $_POST['Location'];
$staffrq = $_POST['Staff_Required'];
$cadetsrq = $_POST['Cadets_Required'];
//insert into database
$sqlinsert = "INSERT INTO Event_Detail (Event_Name, Details, Date, Location, Staff_Required, Cadets_Required) VALUES
('".$name."', '".$details."', '".$date."', '".$location."', '".$staffrq."','".$cadetsrq."')";
$resultinsert = mysql_query($sqlinsert);
if($resultinsert) {
echo "Event Successfully Added...";
}else{
echo "Event Failed to be Added...";
}
}
?>
<table border="1px">
<tr>
<td align="center">
<input style='width:80px;' type='button' value='<'name='previousbutton' onclick ="goLastMonth(<?php echo $month.','.$year?>)">
</td>
<td align="center" colspan="5"><?php echo $monthName." ".$year; ?></td>
<td align="center">
<input style='width:80px;' type='button' value='>'name='nextbutton' onclick ="goNextMonth(<?php echo $month.','.$year?>)">
</td>
</tr>
<tr>
<td align="center" width='80px'>Monday</td>
<td align="center" width='80px'>Tuesday</td>
<td align="center" width='80px'>Wednesday</td>
<td align="center" width='80px'>Thursday</td>
<td align="center" width='80px'>Friday</td>
<td align="center" width='80px'>Saturday</td>
<td align="center" width='80px'>Sunday</td>
</tr>
<tr align="center">
<?php
for($i = 1; $i < $numDays+1; $i++, $counter++){
$timeStamp = strtotime("$i-$month-$year");
//create empty cell until first day of the month
if($i == 1) {
//0=sun, 1=mon, 2=tue, ...
$firstDay = date("w", $timeStamp);
//if sunday change the firstDay to 7
if($firstDay == 0)
$firstDay = 7;
//decrement firstDay by 1
$firstDay--;
for($j = 0; $j < $firstDay; $j++, $counter++) {
echo "<td> </td>";
}
}
//create new row
if($counter % 7 == 0) {
echo"</tr><tr>";
}
$monthstring = $month;
$monthlength = strlen($monthstring);
$daystring = $i;
$daylength = strlen($daystring);
if($monthlength <=1){
$monthstring = "0".$monthstring;
}
if($daylength <=1) {
$daystring = "0".$daystring;
}
$todaysDate = date("d/m/Y");
$dateToCompare = $daystring.'/'.$monthstring.'/'.$year;
//print day number
echo "<td align='center'";
if ($todaysDate == $dateToCompare) {
echo "class='today'";
}else{
$sqlCount = "SELECT * FROM Event_Detail WHERE Date='".$dateToCompare."'";
$noOfEvent = mysql_num_rows(mysql_query($sqlCount));
if($noOfEvents >=1) {
echo "class='event'";
}
}
echo "><a href='".$_SERVER['PHP_SELF']."?day=".$daystring."&month=".$monthstring."&year=".$year."&v=true'>".$i."</a></td>";
}
//fill up the leftover cells of the table
while($counter % 7 != 0) {
echo "<td> </td>";
$counter++;
}
?>
</tr>
</table>
<?php
if(isset($_GET['v'])){
echo "<a href='".$_SERVER['PHP_SELF']."?day=".$day."&month=".$month."&year=".$year."&v=true&f=true'>Add Event</a>";
if(isset($_GET['f'])){
include("eventform.php");
}
$sqlEvent = "SELECT * FROM Event_Detail WHERE Date='".$day."/".$month."/".$year."'";
$resultEvents=mysql_query($sqlEvent);
echo "<hr>";
while($events=mysql_fetch_array($resultEvents)){
echo "Event Name: ".$events['Event_Name']."<br>";
echo "Details: ".$events['Details']."<br>";
echo "Date: ".$events['Date']."<br>";
echo "Location: ".$events['Location']."<br>";
echo "Staff Required: ".$events['Staff_Required']."<br>";
echo "Cadets Required: ".$events['Cadets_Required']."<br>";
}
}
?>
</body>
</html>
eventform.php
<title>Event</title>
<form name="eventform" method="POST" action="<?php $_SERVER['PHP_SELF']; ? >?day=<?php echo $day;?>&month=<?php echo $month;?>&year=<?php echo $year;? >&v=true&add=true">
<table width="400px">
<tr>
<td width="150px">Event Name</td>
<td width="250px"><input type="text" name="Event_Name" required></td>
</tr>
<tr>
<td width="150px">Details</td>
<td width="250px"><textarea name="Details" required></textarea></td>
</tr>
<tr>
<td width='150px'>Location</td>
<td width='250px'><textarea name="Location" required></textarea></td>
</tr>
<tr>
<td width='150px'>Staff Required</td>
<td width='250px'><input type='number' name="Staff_Required" required></td>
</tr>
<tr>
<td width='150px'>Cadets Required</td>
<td width='50px'><input type='number' name="Cadets_Required" required></td>
</tr>
<tr>
<td colspan='2' align='center'><input type='submit' name='btnadd' value='Add Event'></td>
</tr>
I am working on a calendar, using my own code, I can current only get dates to show as booked if they are within the same month.
How would I get things to work if dates go across more than a single month?
These are the main variables that setup the calendar (which come before my while loop):
//Labels
$dayLabels = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$dayMiniLabels = array("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
$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];
};
$currentDate = strtotime("01-$currentMonth-$currentYear");
$prevMonth = sprintf("%02d", $currentMonth - 1);
$nextMonth = sprintf("%02d", $currentMonth + 1);
$prevYear = sprintf("%02d", $currentYear - 1);
$nextYear = sprintf("%02d", $currentYear + 1);
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
$firstDayofMonth = date("D", $currentDate);
$firstDayofMonth = array_search($firstDayofMonth, $dayMiniLabels);
$firstDayofMonth = $firstDayofMonth;
//database values
$bookedStart = array();
$bookedEnd = array();
$bookedUser = array();
if($getBookings = $con->prepare("SELECT userID,bookingStart,bookingEnd FROM bookings WHERE machineID=?")) {
$getBookings->bind_param("i", $_GET['id']);
if($getBookings->execute()) {
$getBookings->bind_result($bookingUserID,$bookingStart,$bookingEnd);
while($getBookings->fetch()) {
array_push($bookedStart, $bookingStart);
array_push($bookedEnd, $bookingEnd);
array_push($bookedUser, $bookingUserID);
};
};
};
$getBookings->close();
//counters
$daysIntoMonth = 0;
$dayCounter = 0;
$startMonth = 0;
This is the current display code for the calendar (the stuff that prints the calendar):
<table class="full grid dayLabels">
<tr>
<?php
foreach($dayLabels as $day) {
echo '<td class="day"><p>' .$day. '</p></td>';
};
?>
</tr>
</table>
<table id="calendar" class="full grid calendar">
<?php
while($daysIntoMonth < $daysInMonth) {
//days into month
$daysIntoMonth++;
$temp_intoMonth = sprintf("%02d", $daysIntoMonth);
$daysIntoMonth = $temp_intoMonth;
//days into week
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
//current calendar date
$calDate = date('d-m-Y', strtotime($daysIntoMonth. '-' .$currentMonth. '-' .$currentYear));
$calTime = strtotime($calDate);
$todaysNumber = date('w', $timeCal);
if($dayCounter == 1) {
echo '<tr>';
};
if($firstDayofMonth != 7) {
while($startMonth < $firstDayofMonth) {
echo '<td class="padding"></td>';
$startMonth++;
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
};
};
if($startKey = in_array($calDate, $bookedStart, true)) {
$booked = true;
echo '
<td class="booked">
<p class="date">' .$daysIntoMonth. '</p>
</td>
';
} else if(in_array($calDate, $bookedEnd, true)) {
$booked = false;
echo '
<td class="booked">
<p class="date">' .$daysIntoMonth. '</p>
</td>
';
} else if($booked == true) {
echo '
<td class="booked">
<p class="date">' .$daysIntoMonth. '</p>
</td>
';
} else {
echo '
<td>
<p class="date">' .$daysIntoMonth. '</p>
</td>
';
};
if($dayCounter == $maxDays) {
echo '</tr>';
$dayCounter = 0;
};
};
?>
</table>
I current look for a start date to set the variable booked variable as true until it comes across an end date. This means that the calendar will only work for dates that are contained within the same month...
How would I go about making the dates work across months?
I ended up completely reworking my calendar system to get this to work the way how I wanted it to:
//Labels
$dayLabels = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$dayMiniLabels = array("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
$monthLables = array("January","February","March","April","May","June","July","August","September","October","November","December");
$forceMonth = $_GET['m'];
$forceYear = $_GET['y'];
$currentDate = date("Y-m-d");
$explodeDate = explode("-", $currentDate);
//Currents
if(isset($forceMonth)) {
if(strlen($forceMonth) == 1) {
$forceMonth = sprintf("%02d", $forceMonth);
};
$currentMonth = $forceMonth;
} else {
$currentMonth = date("m");
};
if(isset($forceYear)) {
if(strlen($forceYear) == 2) {
$dt = DateTime::createFromFormat('y', $forceYear);
$forceYear = $dt->format('Y');
};
$currentYear = $forceYear;
} else {
$currentYear = date("Y");
};
//variables
$monthStart = date($currentYear. '-' .$currentMonth. '-01');
$monthEnd = date($currentYear. '-' .$currentMonth. '-t');
$prevMonth = sprintf("%02d", $currentMonth - 1);
$nextMonth = sprintf("%02d", $currentMonth + 1);
$prevYear = sprintf("%02d", $currentYear - 1);
$nextYear = sprintf("%02d", $currentYear + 1);
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
$firstDayofMonth = date("D", strtotime("01-$currentMonth-$currentYear"));
$firstDayofMonth = array_search($firstDayofMonth, $dayMiniLabels);
$firstDayofMonth = $firstDayofMonth;
if($firstDayofMonth == 0) {
$firstDayofMonth = 7;
};
$bookings = array();
$s = new DateTime($monthStart);
$e = new DateTime("$monthEnd + 1 days");
$oneday = new DateInterval('P1D');
$dp = new DatePeriod($s, $oneday, $e);
foreach ($dp as $d) {
$bookings[$d->format('Y-m-d')] = '';
};
$sql = "SELECT userID
, bookingStart
, bookingEnd
FROM bookings
WHERE machineID = ?
AND bookingStart < ?
AND bookingEnd > ?";
$getBookings = $con->prepare($sql);
$getBookings->bind_param('iss', $_GET['id'], $monthEnd, $monthStart);
$getBookings->execute();
$getBookings->bind_result($uid, $bstart, $bend);
while ($getBookings->fetch()) {
$s = new DateTime(max($bstart, $monthStart));
$e = new DateTime(min($bend, $monthEnd));
$e->modify('+1 day');
$dp = new DatePeriod($s, $oneday, $e);
foreach ($dp as $d) {
$bookings[$d->format('Y-m-d')] = $uid;
};
};
//counters
$dayCount = 0;
$startMonth = 0;
$calDate = 0;
<table class="full grid dayLabels">
<tr>
<?php
foreach($dayLabels as $day) {
echo '<td class="day"><p>' .$day. '</p></td>';
};
?>
</tr>
</table>
<table id="calendar" class="full grid calendar">
<?php
foreach($bookings as $date) {
$dayCount++;
$calDate++;
$calDate = sprintf("%02d", $calDate);
if($dayCount == 1) {
echo '<tr>';
};
if($firstDayofMonth != 7) {
while($startMonth < $firstDayofMonth) {
echo '<td class="padding"></td>';
$startMonth++;
$dayCount++;
$temp_dayCount = sprintf("%02d", $dayCount);
$dayCount = $temp_dayCount;
};
};
if($date != "") {
if($getUserName = $con->prepare("SELECT userFirst,userLast,userEmail FROM users WHERE userID=?")) {
$getUserName->bind_param("i", $date);
$getUserName->execute();
$getUserName->bind_result($userFirst,$userLast,$userEmail);
while($getUserName->fetch()) {
echo '
<td class="booked">
<p>' .$calDate. '</p>
<p>' .$userFirst. ' ' .$userLast. '</p>
</td>
';
};
};
$getUserName->close();
} else {
echo '
<td>
<p>' .$calDate. '</p>
';
if(isset($_SESSION['userID']) && $_SESSION['userPerms'] > 0) {
echo '
<a class="bookNow"></a>
<form class="book" method="post" action="./action.php?a=book">
<input name="userID" type="hidden" value="' .$_SESSION['userID']. '" required />
<input name="machineID" type="hidden" value="' .$id. '" required />
<div class="options">
<a class="fa fa-close"></a>
</div>
<p>Start Date</p>
<input name="startDate" type="text" value="' .$calDate. '-' .$currentMonth. '-' .$currentYear. '" autofocus required />
<p>End Date</p>
<input name="endDate" type="text" value="' .$calDate. '-' .$currentMonth. '-' .$currentYear. '" required />
<p>Project Number</p>
<input name="projectNumber" type="number" placeholder="Project Number" required />
<button class="confirm" type="submit">Submit</button>
</form>
';
};
echo '
</td>
';
};
if($dayCount == 7) {
echo '</tr>';
$dayCount = 0;
};
};
?>
</table>
I'm a beginner at programming and I have to build a website for my school project.
With some help I finally built a calendar: yeey!
But now I have to navigate through my calendar: go through the months and years.
For example, today it is 15 January 2015, I want to go to the year 2016, or to 26 January. I really don't know how to do this...:(
Can somebody help me out please?? I will appreciate it:)
The code of my calendar:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
setlocale(LC_ALL, 'nl_NL');
$today_date = time();
$day = date('d', $today_date);
$month = date('m', $today_date);
$year = date('Y', $today_date);
// Make first day of the month
$first_day = mktime(0,0,0,$month, 1, $year);
// Get name of the month
$title = date('F', $first_day);
// What day of the week is the first day of the month
$day_of_week = date('D', $first_day);
// Lege plekken invullen
switch($day_of_week) { case "Sat": $blank = 6; break;
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;
}
// hoeveel dagen in een maand
$days_in_month = cal_days_in_month(0, $month, $year);
// Bovenkant
echo '<table border="0" cellspacing="0" cellpadding="0" width="1500px"> ';
echo '<tr><th colspan="7" class = "monthname"> ' .$title . ' ' . $year. ' </th></tr>';
echo '<tr> <td width="50" class="weekend">Zondag</td>
<td width="50" class = "dag">Maandag</td>
<td width="50" class = "dag">Dinsdag</td>
<td width="50" class = "dag">Woensdag</td>
<td width="50" class = "dag">Donderdag</td>
<td width="50" class = "dag">Vrijdag</td>
<td width="50" class="weekend">Zaterdag</td>
</tr>';
$day_count = 1;
echo '<tr>';
// De dagen die er in een maand niet zijn invullen met een leeg vak
while ( $blank > 0 ) {
if ($day_count == 1 || $day_count == 7) {
echo '<td class="weekend"> </td>';
} else
{echo '<td></td>'; }
$blank = $blank - 1;
$day_count++;
}
$day_num = 1;
while ($day_num <= $days_in_month) { if ($day_count == 1 || $day_count == 7) { if ($day_num == $day) { echo ' <td class="weekend today">
' .$day_num. '
</td>'; } else { echo '
<td class="weekend">
' .$day_num. '
</td>'; } } else { if ($day_num == $day) { echo '
<td class="today">
' .$day_num. '
</td>'; } else { echo '
<td>
' .$day_num. '
</td>'; } } $day_num++; $day_count++;
// Seperate the week out onto new lines
if ($day_count > 7) { echo '</tr>
<tr>
'; $day_count = 1; } }
// Blank out days not needed at the end of the month
while ($day_count > 1 && $day_count <= 7) { if ($day_count == 1 || $day_count == 7) { echo '<td class="weekend">
</td>'; } else
{ echo '<td>
</td>'; } $day_count++; }
// End the table
echo '</tr></table>';
?>
</div>
</body>
</html>
you can do this with 2 Get Variables. m (month) and y (year).
change your rows:
$month = date('m', $today_date);
$year = date('Y', $today_date);
into:
$month = (isset($_GET['m'])) ? $_GET['m'] : date('m', $today_date);
$year = (isset($_GET['y'])) ? $_GET['y'] : date('Y', $today_date);
Now you can call your script with month and year:
?m=3&y=2014
is your view for march 2014.
And you can create Next and Previous links which calling your script with the y and m Get Variables.
Try to use mktime() instead of time().
The parameters for the mktime function should than be transmitted threw the GET variables.