I have seen this question posted over and over again here, yet nobody has thoroughly answered this question. I wrote this tutorial so that new members to this site will have the opportunity to have their calendar scripts taken to the next level.
In this tutorial, I will show you how to create a calendar application that has the ability to add / remove events on a given day. We will be using MySQL as our database application to store and track events.
This tutorial is written for people who understand basic programming theory, and some of the PHP structure. I will discuss the beginner (and some more advanced) techniques, and apply them in a real world application.
Requirements:
- Programming Logic
- Basic PHP knowledge
- Basic Javascript knowledge
- PHP supported server
- MySQL server
- 2 files (calendar.php and event.php)
- Notepad (or IDE of choice)
Index:
- Section 1
- Part 1 - Checking User Input
- Part 2 - Building the HTML Form
- Part 3 - Creating the Calendar
- Part 1 - Checking User Input
- Section 2
- Part 4 - Adding Events to the Calendar
- Part 5 - Showing / Adding Events via. Pop-Up
- Part 4 - Adding Events to the Calendar
Section 1 - Building the Calendar
Part 1 - Checking User Input
We will be asking the user for the month and year that they want to view of the calendar, so the first thing we need to do is figure out what part of the calendar will be generated. When the user views the calendar for the first time, we will not have any information, so we need to tell the script how to handle accepting the variables for the month and year.
- Checking User Input for the Calendar Script:
<?php
if ((!isset($_POST['month'])) || (!isset($_POST['year']))) {
$nowArray = getdate();
$month = $nowArray['mon'];
$year = $nowArray['year'];
} else {
$month = $_POST['month'];
$year = $_POST['year'];
}
$start = mktime(12,0,0,$month,1,$year);
$firstDayArray = getdate($start);
?>
What we are doing here is first, checking if the user has submitted any information. If they have, we will take the $_POST['month']; and $_POST['year']; variables and store them for processing. If they haven't submitted any form data, we know that this must be the first time they have loaded our application, and we will set the selected date and year as the current.
The function mktime(); is used to easily format string data (our $_POST variables) as a UNIX Timestamp.
We also used getdate(); as seen on line 3, to create an associative array based on the current time.
Part 2 - Building the HTML Form
Now that we have our method of accepting the users input using PHP, we need to create an interface by which users can select the month and year. We will be using pull down menus, also known as the SELECT element in HTML. We could use HTML to do this, but since we want to keep our menu at the currently selected month / year, we will use PHP to dynamically create the menu.
<html>
<head>
<title><?php echo "Calendar: ".$firstDayArray['month']."" . $firstDayArray['year']; ?></title>
</head>
<body>
<h1>Select a Month/Year</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="month">
<?php
$months = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
for ($x=1; $x<=count($months); $x++){
echo "<option value=\"$x\"";
if ($x == $month){
echo " selected";
}
echo ">".$months[$x-1]."</option>";
}
?>
</select>
<select name="year">
<?php
for ($x=1980; $x<=2010; $x++){
echo "<option";
if ($x == $year){
echo " selected";
}
echo ">$x</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go!">
</form>
</body>
</html>
The main theory here is our for(){}; loop. As previously mentioned, instead of using HTML to hard-code the months as static information, we are using PHP to create an array that stores the months of the year. Doing so, we can use our $_POST information to keep the corresponding month / year selected throughout the process (until it is changed by the user).
Also, we can see the use of dynamic content on our page. Notice the <title> contains our month and year. Small things like this all add up to making a dynamic, and nice looking page.
So we now have a form that can send the month and year parameters to itself.
Part 3 - Creating the Calendar
Now that we have completed the selection menu, we are ready to build the calendar. PHP has no built in calendar(); functions, so we will need to create a table and populate it with the corresponding days manually.
<?php
$days = Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
echo "<table border=\"1\" cellpadding=\"3\"><tr>\n";
foreach ($days as $day){
echo "<td style=\"background-color: #CCCCCC; text-align: center; width: 14% \"><strong>$day</strong></td>\n";
}
for ($count=0; $count < (6*7); $count++){
$dayArray = getdate($start);
if (($count % 7) == 0){
if ($dayArray['mon'] != $month){
break;
} else {
echo "</tr><tr>\n";
}
}
if ($count < $firstDayArray['wday'] || $dayArray['mon'] != $month){
echo "<td> </td>\n";
} else {
echo "<td>".$dayArray['mday']." </td>\n";
$start += ADAY;
}
}
echo "</tr></table>";
?>
</body>
</html>
Here, we are using a for loop to determine how many days are in each week, and what days need to be printed along the way. As far as the logic goes, this is the same as any other loop, with specific conditions that detail where things go where they need to go.
Code so far:
<?php
if ((!isset($_POST['month'])) || (!isset($_POST['year']))) {
$nowArray = getdate();
$month = $nowArray['mon'];
$year = $nowArray['year'];
} else {
$month = $_POST['month'];
$year = $_POST['year'];
}
$start = mktime(12,0,0,$month,1,$year);
$firstDayArray = getdate($start);
?>
<html>
<head>
<title><?php echo "Calendar: ".$firstDayArray['month']."" . $firstDayArray['year']; ?></title>
</head>
<body>
<h1>Select a Month/Year</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="month">
<?php
$months = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
for ($x=1; $x<=count($months); $x++){
echo "<option value=\"$x\"";
if ($x == $month){
echo " selected";
}
echo ">".$months[$x-1]."</option>";
}
?>
</select>
<select name="year">
<?php
for ($x=1980; $x<=2010; $x++){
echo "<option";
if ($x == $year){
echo " selected";
}
echo ">$x</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go!">
</form>
<br />
<?php
$days = Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
echo "<table border=\"1\" cellpadding=\"3\"><tr>\n";
foreach ($days as $day){
echo "<td style=\"background-color: #CCCCCC; text-align: center; width: 14% \"><strong>$day</strong></td>\n";
}
for ($count=0; $count < (6*7); $count++){
$dayArray = getdate($start);
if (($count % 7) == 0){
if ($dayArray['mon'] != $month){
break;
} else {
echo "</tr><tr>\n";
}
}
if ($count < $firstDayArray['wday'] || $dayArray['mon'] != $month){
echo "<td> </td>\n";
} else {
echo "<td>".$dayArray['mday']." </td>\n";
$start += ADAY;
}
}
echo "</tr></table>";
?>
</body>
</html>
This calendar is all pretty and nice, but it is missing something. We are here to learn how to add events to a calendar... which is where we go next!
Section 2 - Database Driven Events
This second part is an extention to the Calendar Script. The calendar as it is up to this point is 100% functional and can stand alone without continuing. The point of the second section is: to teach you how to modify what you've done by using MySQL and a bit more advanced PHP, to create a Calendar Management System to track events.
Part 4 - Adding Events to the Calendar
First things first, as you most likely already know, we need a database. The purpose of the database is to store our events, and deliver dynamic content to our calendar application. In this tutorial, we will be using MySQL.
The calendar_events table will have fields for the start date and time, the name of the event, and a short description of the event.
CREATE TABLE calendar_events ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, event_title VARCHAR (25), event_shortdesc VARCHAR (255), event_start DATETIME );
Now that we have created our database table, we are ready to start the design of adding events. By my personal preference, I decided that the events will load in a small pop-out window. I like the way this looks / acts better than navigating away from our actual calendar... but if you should choose to do so otherwise, this would be a small fix. I won't cover this here, but it shouldn't be too hard to figure out
<script type="text/javascript">
function eventWindow(url){
event_popupWin = window.open(url, 'event', 'resizable=yes, scrollbars=yes, toolbar=no,width=400,height=400');
event_popupWin.opener = self;
}
</script>
This code as you can see simply defines the window attributes that will open when we are ready to view our events.
The next step we must take is to modify the Calendar creation script to add Hyperlink URL's on the days to show / add events. Furthermore, we must design a system that connects to our MySQL database and prints any events on the calendar so we can see which days have stored events. This will require some modifications, mostly around lines 64-68.
calendar.php
<?php
// At line 2 of our calendar.php script, add the MySQL connection information:
$mysql = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $mysql) or die(mysql_error());
// Now we need to define "A DAY", which will be used later in the script:
define("ADAY", (60*60*24));
// The rest of the script will stay the same until about line 82
if ((!isset($_POST['month'])) || (!isset($_POST['year']))) {
$nowArray = getdate();
$month = $nowArray['mon'];
$year = $nowArray['year'];
} else {
$month = $_POST['month'];
$year = $_POST['year'];
}
$start = mktime(12,0,0,$month,1,$year);
$firstDayArray = getdate($start);
?>
<html>
<head>
<title><?php echo "Calendar: ".$firstDayArray['month']."" . $firstDayArray['year']; ?></title>
</head>
<script type="text/javascript">
function eventWindow(url) {
event_popupWin = window.open(url, 'event', 'resizable=yes,scrollbars=yes,toolbar=no,width=400,height=400');
event_popupWin.opener = self;
}
</script>
<body>
<h1>Select a Month/Year</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="month">
<?php
$months = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
for ($x=1; $x<=count($months); $x++){
echo "<option value=\"$x\"";
if ($x == $month){
echo " selected";
}
echo ">".$months[$x-1]."</option>";
}
?>
</select>
<select name="year">
<?php
for ($x=1980; $x<=2010; $x++){
echo "<option";
if ($x == $year){
echo " selected";
}
echo ">$x</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go!">
</form>
<br />
<?php
$days = Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
echo "<table border=\"1\" cellpadding=\"5\"><tr>\n";
foreach ($days as $day) {
echo "<td style=\"background-color: #CCCCCC; text-align: center; width: 14%\">
<strong>$day</strong></td>\n";
}
for ($count=0; $count < (6*7); $count++) {
$dayArray = getdate($start);
if (($count % 7) == 0) {
if ($dayArray["mon"] != $month) {
break;
} else {
echo "</tr><tr>\n";
}
}
if ($count < $firstDayArray["wday"] || $dayArray["mon"] != $month) {
echo "<td> </td>\n";
} else {
$chkEvent_sql = "SELECT event_title FROM calendar_events WHERE month(event_start) = '".$month."' AND dayofmonth(event_start) = '".$dayArray["mday"]."' AND year(event_start) = '".$year."' ORDER BY event_start";
$chkEvent_res = mysql_query($chkEvent_sql, $mysql) or die(mysql_error($mysql));
if (mysql_num_rows($chkEvent_res) > 0) {
$event_title = "<br/>";
while ($ev = mysql_fetch_array($chkEvent_res)) {
$event_title .= stripslashes($ev["event_title"])."<br/>";
}
mysql_free_result($chkEvent_res);
} else {
$event_title = "";
}
echo "<td valign=\"top\"><a href=\"java script:eventWindow('event.php?m=".$month."&d=".$dayArray["mday"]."&y=$year');\">".$dayArray["mday"]."</a><br/>".$event_title."</td>\n";
unset($event_title);
$start += ADAY;
}
}
echo "</tr></table>";
mysql_close($mysql);
?>
</body>
</html>
Now that we have modified everything in the calendar script to support Events, the only thing left to do is add our event.php script! This will take most of the basic principals we have already discussed and use them to add data to our database. Since our Calendar already supports database driven content, this will be the last step in our process!
Part 5 - Showing / Adding Events via. Pop-Up
Create a new file called: event.php
<html>
<head>
<title>Show / Add Events</title>
</head>
<body>
<h1>Show / Add Events</h1>
<?php
$mysql = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $mysql) or die(mysql_error());
// Add our new events
if ($_POST){
$m = $_POST['m'];
$d = $_POST['d'];
$y = $_POST['y'];
// Formatting for SQL datetime (if this is edited, it will NOT work.)
$event_date = $y."-".$m."-".$d." ".$_POST["event_time_hh"].":".$_POST["event_time_mm"].":00";
$insEvent_sql = "INSERT INTO calendar_events (event_title,
event_shortdesc, event_start) VALUES('
".$_POST["event_title"]."',
'".$_POST["event_shortdesc"]."', '$event_date')";
$insEvent_res = mysql_query($insEvent_sql, $mysql)
or die(mysql_error($mysql));
} else {
$m = $_GET['m'];
$d = $_GET['d'];
$y = $_GET['y'];
}
// Show the events for this day:
$getEvent_sql = "SELECT event_title, event_shortdesc,
date_format(event_start, '%l:%i %p') as fmt_date FROM
calendar_events WHERE month(event_start) = '".$m."'
AND dayofmonth(event_start) = '".$d."' AND
year(event_start)= '".$y."' ORDER BY event_start";
$getEvent_res = mysql_query($getEvent_sql, $mysql)
or die(mysql_error($mysql));
if (mysql_num_rows($getEvent_res) > 0){
$event_txt = "<ul>";
while($ev = @mysql_fetch_array($getEvent_res)){
$event_title = stripslashes($ev["event_title"]);
$event_shortdesc = stripslashes($ev["event_shortdesc"]);
$fmt_date = $ev["fmt_date"];
$event_txt .= "<li><strong>".$fmt_date."</strong>:
".$event_title."<br/>".$event_shortdesc."</li>";
}
$event_txt .="</ul>";
mysql_free_result($getEvent_res);
} else {
$event_txt = "";
}
mysql_close($mysql);
if ($event_txt != ""){
echo "<p><strong>Today's Events:</strong></p>
$event_txt
<hr/>";
}
// Show form for adding the event:
echo "
<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">
<p><strong>Add Event:</strong><br/>
Complete the form below then press the submit button when you are done.</p>
<p><strong>Event Title:</strong><br/>
<input type=\"text\" name=\"event_title\" size=\"25\" maxlength=\"25\"/></p>
<p><strong>Event Description:</strong<br/>
<input type=\"text\" name=\"event_shortdesc\" size=\"25\" maxlength=\"255\"/></p>
<p><strong>Event Time (hh:mm):</strong><br/>
<select name=\"event_time_hh\">";
for ($x=1; $x<=24; $x++){
echo "<option value=\"$x\">$x</option>";
}
echo "</select> :
<select name=\"event_time_mm\">
<option value=\"00\">00</option>
<option value=\"15\">15</option>
<option value=\"30\">30</option>
<option value=\"45\">45</option>
</select>
<input type=\"hidden\" name=\"m\" value=\"".$m."\">
<input type=\"hidden\" name=\"d\" value=\"".$d."\">
<input type=\"hidden\" name=\"y\" value=\"".$y."\">
<br/><br/>
<input type=\"submit\" name=\"submit\" value=\"Add Event!\">
</form>";
?>
</body>
</html>
There we have it! Lines 29-35 send the query and return all the records that correspond to events on the given day. We display the entries on lines 37-51. The form for submitting new events can be found on lines 61-87.
I would like to thank everyone at D.I.C. for this article. I have been programming for almost 12 years now, and without D.I.C. I wouldn't have kept a solid interest in programming. I am now re-attending college for my Computer Science degree, and I'm leaps and bounds above most of the people in the program. This summer I am joining a robotics team as the main physics and collision detection programmer... so look forward to seeing more and more tutorials from things I learn along the way!





MultiQuote





|