Add Events to the PHP Calendar

By  on  

In a previous blog post I detailed how to create a basic calendar using PHP and then showed you how to add controls to that calendar. This post will detail how you may efficiently pull events from a MySQL table and display those events within the calendar.

The Event-Building PHP / SQL

$events = array();
$query = "SELECT title, DATE_FORMAT(event_date,'%Y-%m-%D') AS event_date FROM events WHERE event_date LIKE '$year-$month%'";
$result = mysql_query($query,$db_link) or die('cannot get results!');
while($row = mysql_fetch_assoc($result)) {
	$events[$row['event_date']][] = $row;
}

Feel free to create the "events" table with any structure you'd like. The event date may be held in a DATE or DATETIME field. What's important is that the date is exported in YYYY-MM-DD format.

The CSS

div.day-number	 { 
	background:#999; 
	position:absolute; 
	z-index:2; 
	top:-5px; 
	right:-25px; 
	padding:5px; 
	color:#fff; 
	font-weight:bold; 
	width:20px; 
	text-align:center; 
}
td.calendar-day, td.calendar-day-np { 
	width:120px; 
	padding:5px 25px 5px 5px; 
	border-bottom:1px solid #999; 
	border-right:1px solid #999; 
}

The CSS code for the item will need to change slightly to accommodate for absolute positioning of the day. We need to apply absolute positioning so that the event text doesn't disrupt the placement of the day.

The PHP - Draw Calendar

PHP Notice: Use of undefined constant replace_angles - assumed 'replace_angles' in /private/tmp/temp_textmate.keFHeG on line 12
/* draws a calendar */
function draw_calendar($month,$year,$events = array()){

	/* 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">&nbsp;</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"><div style="position:relative;height:100px;">';
			/* add in the day number */
			$calendar.= '<div class="day-number">'.$list_day.'</div>';
			
			$event_day = $year.'-'.$month.'-'.$list_day;
			if(isset($events[$event_day])) {
				foreach($events[$event_day] as $event) {
					$calendar.= '<div class="event">'.$event['title'].'</div>';
				}
			}
			else {
				$calendar.= str_repeat('<p>&nbsp;</p>',2);
			}
		$calendar.= '</div></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">&nbsp;</td>';
		endfor;
	endif;

	/* final row */
	$calendar.= '</tr>';
	

	/* end the table */
	$calendar.= '</table>';

	/** DEBUG **/
	$calendar = str_replace('</td>','</td>'."\n",$calendar);
	$calendar = str_replace('</tr>','</tr>'."\n",$calendar);
	
	/* all done, return result */
	return $calendar;
}

function random_number() {
	srand(time());
	return (rand() % 7);
}

/* date settings */
$month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
$year = (int)  ($_GET['year'] ? $_GET['year'] : date('Y'));

/* select month control */
$select_month_control = '<select name="month" id="month">';
for($x = 1; $x <= 12; $x++) {
	$select_month_control.= '<option value="'.$x.'"'.($x != $month ? '' : ' selected="selected"').'>'.date('F',mktime(0,0,0,$x,1,$year)).'</option>';
}
$select_month_control.= '</select>';

/* select year control */
$year_range = 7;
$select_year_control = '<select name="year" id="year">';
for($x = ($year-floor($year_range/2)); $x <= ($year+floor($year_range/2)); $x++) {
	$select_year_control.= '<option value="'.$x.'"'.($x != $year ? '' : ' selected="selected"').'>'.$x.'</option>';
}
$select_year_control.= '</select>';

/* "next month" control */
$next_month_link = '<a href="?month='.($month != 12 ? $month + 1 : 1).'&year='.($month != 12 ? $year : $year + 1).'" class="control">Next Month &gt;&gt;</a>';

/* "previous month" control */
$previous_month_link = '<a href="?month='.($month != 1 ? $month - 1 : 12).'&year='.($month != 1 ? $year : $year - 1).'" class="control">&lt;&lt; 	Previous Month</a>';


/* bringing the controls together */
$controls = '<form method="get">'.$select_month_control.$select_year_control.'&nbsp;<input type="submit" name="submit" value="Go" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$previous_month_link.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$next_month_link.' </form>';

/* get all events for the given month */
$events = array();
$query = &quot;SELECT title, DATE_FORMAT(event_date,'%Y-%m-%D') AS event_date FROM events WHERE event_date LIKE '$year-$month%'&quot;;
$result = mysql_query($query,$db_link) or die('cannot get results!');
while($row = mysql_fetch_assoc($result)) {
	$events[$row['event_date']][] = $row;
}

echo '<h2 style="float:left; padding-right:30px;">'.date('F',mktime(0,0,0,$month,1,$year)).' '.$year.'</h2>';
echo '<div style="float:left;">'.$controls.'</div>';
echo '<div style="clear:both;"></div>';
echo draw_calendar($month,$year,$events);
echo '<br /><br />';

We retrieve the events for the given month BEFORE calling the draw_calendar function. Doing so will allow us to avoid 27+ queries by not querying for each day. The events array is a key=>value array where the key is the date and the value is an array of events for that day. We pass that event into the draw_calendar function and when it gets to the day display DIV we run a FOREACH loop to output any events.

Tada! Happy calendar-creating!

Recent Features

Incredible Demos

Discussion

  1. Thanks for the tutorial, this is a great resource for web developers just starting out!

  2. One more great tutorial!!! Thanks David

  3. Good tutorial. If only this would’ve been released 2 weeks ago. I was still working on a calendar bases project back then. :P

  4. Good tut,

    I think there is a bud at line 115
    $events[$row[‘event_date’]] = $row;

    Should be:
    $events[$row[‘event_date’]][]= $row;

  5. Right on SiTo — updated.

    • I try your hard work. I am getting nice calendar but itdoesnt print the ecent

    • Kumar

      sorry spell mistake. it doesn’t print the events?

  6. Badass. I was just randomly thinking about this the other night… how to avoid making a zillion queries when building a calendar on the fly. Makes perfect sense to query for the events first, then conditionally check for those events when building the calendar day cells.

    I should show you how I handled this on a site about a year ago, almost funny now. I output a hidden list of event dates below the calendar, and then use JavaScript to read them and plug them back up into the calendar area.

  7. EmEhRKay

    David, did you ever check out the class that I wrote around this calendar? I spammed the original post with a bunch of links to it as I was working on it.

    Here is what I use today:

    http://pastie.org/748060

    Thanks again, I use the fuck out of it

    • Nice. i will use it for my next proyect, so thanks.

  8. Thanks David.
    Can you write an article about how to add events using php/mysql/ajax (hopefully with jquery)? Plz plz plz?

  9. Jason

    Awsome I have been waiting for this! I have a use for this in the near future but not at the very moment, does anyone have a demo of this

  10. Viko Campbells

    hello, i have some problems with the function mysql_fetch_assoc, i dont know if its only me, or i have the wrong version but i do some change and it works just right, this is what u have:

    while($row = mysql_fetch_assoc()) {
    	$events[$row['time']][] = $row;
    }
    

    what i do is:

    while($row = mysql_fetch_assoc($result)) {
    	$events[$row['time']][] = $row;
    }
    
  11. Viko Campbells

    oh sorry, i change the name of the time column from event_date to time

  12. Gary

    I have the DB built, but can’t get the two connected. Any ideas on how to connect the two?

  13. Colby Smart

    The database is connecting and I am able to print the events outside the calendar but they are not showing within the calendar. Any ideas?

  14. William Rouse

    Colby:
    I took some time to work on this today and I am having a problem like yours. Is your events array empty?
    My result set and events array both seem to be empty although the query I wrote works when using a MySQL editor.

  15. William Rouse

    Well, I know what my problem is, but I don’t know how to fix it.
    The first part:
    $query = “SELECT title, DATE_FORMAT(event_date’%Y-%c-%e’) AS event_date FROM events WHERE event_date LIKE ‘$year-$month%'”;
    There is a missing comma “,” between event_date and the format type.

    The second part is what I don’t know how to fix.
    When you resolve the query string the $month value will be a single digit for months January through September and will not match the value in my database.
    I made a test of this by inserting data into the previous month 12-2009 and it works perfectly.
    So I am trying to figure out how to convert the month value in the query string to produce a two digit month like 01, 02 …

  16. @William Rouse: Try this:

    $month = str_pad($month,2,'0', STR_PAD_LEFT);
  17. William Rouse

    @David Walsh: The problem is between the events array and the variable $event_day at the line “if(isset($events[$event_day])) {“.
    “event_day = 2010-01-1 while events is “2010-1-1”.

    $events = :Array ( [2010-1-1] => Array ( [0] => Array ( [title] => Former U.S. State Department official Alger Hiss [event_date] => 2010-1-1 ) ) [2010-1-5] => Array ( [0] => Array ( [title] => Universe created at 8:00 PM according [event_date] => 2010-1-5 ) )
    The test to output to the calendar not met at
    “if(isset($events[$event_day])) {” and the text is not sent to the browser. Hope that clarifes it.

    • Zachary

      I too have the same issue. From what David wrote is event_date and suddenly it became event_day. I am still having problems putting the eventName/title inside the day. Plus i can’t even add the event inside the $event(). Please help, i really need help as its for my school project…Reply soon…Thanks in advance.

  18. William Rouse

    I wanted to add that it seems when the data is returned at:

     while($row = mysql_fetch_assoc($result)) {
                $events[$row['event_date']][] = $row;
            }
    

    That is where the formatting needs to occur.

  19. @William Rouse: I’ve updated my post. Try setting the date format in the SQL query to “%Y-%m-%D”

  20. William Rouse

    @David Walsh:
    ‘%Y-%m-%d this works for me.

    “%Y-%m-%D” attaches English suffix like st, nd …
    Thanks for the weekend work.
    WBR

  21. Colby Smart

    @William Rouse: Thank you William. I get data when the array is printed outside of the calendar so I know I am pinging the database correctly. However, there may be a formatting issue with my date display. Thanks for looking into this.

  22. Colby Smart

    @William Rouse & David Walsh: Yes, thank you both for your efforts. This script has been a nice challenge to work on and will come in handy for a project I am working on.

  23. Colby Smart

    @David Walsh: I am now able to get data onto the calendar, but no data shows up on single digit months. My SQL format is %Y-%m-%d which is includes leading zeros.

    Is $month = str_pad($month,2,’0′, STR_PAD_LEFT); necessary? If so where might it fall in the code?

  24. William Rouse

    Yup, you’ll need to add a stri_pad.
    Here is a bit of code to give you the location:

    for($list_day = 1; $list_day <= $days_in_month; $list_day++):
                    $calendar.= '';
                    /* add in the day number */
                    if($list_day < 10) {
                        $list_day = str_pad($list_day, 2, '0', STR_PAD_LEFT);
                    }
                    $calendar.= ''.$list_day.'';
    
                    $event_day = $year.'-'.$month.'-'.$list_day;
    

    Hope that helps
    WBR

  25. CS

    @WBR Thanks,

    Interesting, I added it right above the the $query

    /* get all events for the given month */
    $month = str_pad($month,2,"0", STR_PAD_LEFT);
    $events = array();
    $query = "SELECT course_title, DATE_FORMAT(DTSTART,'%Y-%m-%d')
    

    The data now populates for current month and all previous months (14 total). Interestingly enough no data is showing for future months. Getting close though.

  26. William Rouse

    I have it in two places.
    1) where you have it located.
    2) In the function draw_calendar where I suggested in my last note. Search for the comment “keep going with days” and then look at my last note.

    I just put in some events for 02/2010 as a quick test and they are being picked up. I have not entered any data beyond February 2010. Will check that out later tonight when I have time.

    Try to locate the second location and let me know if that helps
    WBR

  27. I still can’t get anything from the db. I did get it to connect, but can’t get anything on the calendar.

  28. CS

    @William Rouse: Outstanding, adding it to the second location got me going. Thanks again William.

  29. Gary

    @William Rouse:
    Yes, thanks for your help as well. Everything seems to be working!

  30. Gary

    Would it be very difficult to add a recurring event to this calendar? It’s working wonderfuly but I would like to be able to add the recurring event. Any ideas on how this would be done?

  31. Marc

    Dude, you gotta indent your code. spend more time trying to track down closing parenthesis in case of a problem than actually working at the problem.

  32. arcticfire

    i am having trouble getting my events to show up. i need some help. i can get the calendar to show up, but the actual events aren’t being displayed.
    anyone have an idea?

  33. Agent007

    for the event calendar, i have done querying the database and showing the results, but how would I “echo” in row, it in the right day of the event?
    ex. Celebration week – Jan 01, 2010

  34. cdoggyd

    @David Walsh: Would this calendar allow for events spanning multiple days? Do you have a *suggested* MySQL table layout?

    @EmEhRKay: Any documentation for the class?

  35. Darin Slagle

    I’m working on a website for a small science museum in my town. I’ve been studying the calendar here and have got the basic version with the controls working. My roadblock is that the museum doesn’t have a database program or anything like that. I’ve been searching around for some way to do an event calendar based off of a flat file but I’ve come up with nothing. So if anyone has any advice for me or solutions I would love to hear them.

  36. bman

    I can’t get this to work. I’m connecting to the DB but it’s not building the calendar with this (the events) version.

  37. bman

    Sorry about the post above… didn’t think that would work and it didn’t.

    Here’s a link:

    http://www.codesend.com/view/8c20734d0c26121cc586a59bad27dd54/

  38. Chi Melville

    @Colby Smart:

    Colby – I seem to be stuck at the same point you were – I can get the query to work outside the calendar but can’t get the data to popluate the calendar.

    What did you do to get it to work? Could you send me the working code?

  39. bman

    @Chi Melville:

    Change the uppercase “D” to a lowercase “d” in the query. Uppercase returns a day such as 1st, 2nd, etc. The lowercase returns 01, 02, etc.

  40. bman

    Sorry, I posted before I read his issue, but I had a similar issue, I’m not finished customizing this, I’m on a separate project at the moment but have a look.

    http://www.codesend.com/view/af65e27a05405a256a2391334d46f014/

    I started to do an additional query for each expanded event, but then thought I’d just hide each expanded event and use reveal to expand it. I haven’t finished it but there should be enough there for you to figure out where you’re going wrong.

  41. Hay Guys,
    how can i change the month to germany or any lang?

  42. Bo Gunnarson

    I have now implementet this calendar on my site, but i doesn’t show the dates, it only shows the 32’th.

    Any suggestions?

  43. waspinator

    this code only shows ‘Sunday’,’Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’ and the 31st day.

    How is this code supposed to do anything if we keep on adding ” to calendar? The calendar in the first 2 examples worked for me …

    • Brad

      Same here. Is something missing from the above PHP code example? I’m thinking it needs to be merged with code from the previous page. I know my database is connected.

      I’ll admit it: I’m lazy and I just want to copy and paste : )

      Thanks for your help, David!

  44. 10ddmike

    @waspinator:
    I’m having the same output. Any solutions?

  45. @10ddmike: @Bo Gunnarson: @ waspinator

    It looks like something may have gone wrong with the code upload. I’ve been messing with this all day and I just noticed that the HTML for the calendar build ( $calendar.=’ ‘ ) is not outputting any table tags etc. So, it’s basically appending nothingness to the $calendar HTML string that’s output. I’m in the middle of adding them all back in from the previous posts, I’ll let you know if that actually works. I’m about halfway through and I have a ugly looking bunch of calendar rows now, but at least it’s better than the 32th of the month…

  46. Ooops. Just noticed that this probably isn’t going to work (adding in the HTML because the script builds in the dates and events and outputs all the HTML (supposedly) at the end. I think that’s where the problem is but it will take more time than copying and pasting to figure it out. Still, love to use David’s free code so I’m not complainin’.

  47. CaptainCaveMan

    Yeah I’m stuck also, I decided to go back to the previous code to try to figure it out. I am trying to query the db and if there is an event for the day, I want to add a little image to the calendar day instead of the actual text. Then I want to have the image be a link that will list the days events below the calendar.
    I have it all pretty much squared away except for getting the images to display in the calendar.
    I’ve been trying to replace this line

    $calendar.= str_repeat('',2);
    

    but I can’t figure out how to get the images to list on the correct day
    any ideas?

  48. lynsey93

    http://marchingrebels.org/Testing/Calendar2.php

    This is all I’m getting. Any suggestions?

    • By doing a “View Source”, I can see your PHP is all sorts of messed up. PHP is displaying within the HTML source.

    • Lynsey93

      How can I fix that? All I did was copy and paste it and change the php for my own database. This code is a bit more advanced than I’m used to.

  49. Jay

    I am having the same issue as some above where the event is not showing up in the calendar. I have changed it as suggested above with the date formatting. I am getting the events from the database when I issue a print_r for the $events.
    Array ( [2010-08-16] => Array ( [0] => Array ( [title] => Starts [event_date] => 2010-08-16 ) ) [2010-08-29] => Array ( [0] => Array ( [title] => Ends [event_date] => 2010-08-29 ) ) )

    I think there is an issue in this section:
    $event_day = $year.’-‘.$month.’-‘.$list_day;
    if(isset($events[$event_day])) {
    foreach($events[$event_day] as $event) {
    $calendar.= ”.$event[‘title’].”;
    }
    }

    I want it die here so I can see where it is going wrong but I am not sure where to put the ‘or die’ statement. Any suggestions?

    Thanks

    • imjustthiscool

      How did you get it working if you don’t mind my asking, my events aren’t showing up, I have done the month thing and everything but argh. It’s a bit unclear to me. :( I wish coding were a whole lot easier haha.

  50. Jay

    Nevermind. One of those d’uh moments. It is working now.

    David, nice tutorial on the calendar. It is exactly what I was looking for to add to my neighborhood website. It was also nice to be able to put into practice what I have been learning in class. A another thanks to all the others with help on the extras.

  51. Hey David,

    I’ve used your calendar in an events plugin I’ve been writing for a WordPress/BuddyPress . You can check it out here if you feel like it:
    http://buddyvents.jobboardr.com/events/calendar/

    I’ve had to change quite a bit to make events work and added support for events spanning multiple days, but esentially it’s still your calendar, so thanks a lot!

  52. Reesha

    I want its database structure also.. can u help me??

  53. Is this code supposed to work as is, or does it have to be merged somehow with the previous tutorial? There are a lot of statements above that run through a loop appending nothing to the $calendar variable.

  54. I got the original code working, and it shows the calendar table with the day numbers inserted. I have my database working and can echo the contents outside the calendar. When I run the new code with the database info inserted, however, I get a display of the day names followed by two table squares, the last of which contains “31”.

    It appears to me that the first part of the draw_calendar function goes through the days of the month without creating anything printable Then at the end it creates a printable table without scanning the days. That seems consistent results I am getting.

    I see above that others have had the same problem. Has anyone fixed it?

  55. ananthi

    THIS IS MY CODING.IN THIS I WANT TO BOOK EVENT AND THAT PARTICULAR DATE MUST BE FILLED BY ANY COLOR.IN THIS WHERE I WANT TO FIX THE EVENT CODING.ANY ONE KNOW ABOUT THIS REPLY ME.MY EMAIL IS ananthisanthi2@gmail.com.

    <?php
    include("connect.php");
    include("functions.php");
    echo 'Calendar';
    
    	$month = date("n/Y");
    
    	if (isset($_GET['month']))
    	{
    	@$month = clean($_GET['month']);
    	$month = preg_replace("#[^0-9/]#", "", $month);
    	}
    	//echo "month is $month";
    	
    	if (empty($month))
    	die("Please enter a month.");
    	
    	$k = explode("/",$month);	
    	
    	$link = "SELECT * FROM calendar WHERE month='$month'";
    	$res = mysql_query($link) or die(mysql_error());
    	$info = mysql_fetch_assoc($res);
    	if (!mysql_num_rows($res)) die("There is no records for this month.");
    	
    	$startday = $info['start_day'];
    	$days = $info['total_days'] + $startday;
    	
    	$stuff = "SELECT * FROM events WHERE date LIKE '$k[0]%$k[1]'";
    	$show = mysql_query($stuff) or die(mysql_error());
    	$total = mysql_num_rows($show);
    
    	$x = $startday;	
    	
    	$spot = $startday;	
    	
    	while ($r = mysql_fetch_assoc($show))
    	{	
    		$date = $r['date'];
    		$date1 = $r['date1'];
    	
    		$name = $r['name'];
    		$des = $r['des'];
    		
    		$date = explode("-",$date);
    		$date = $date[1];		
    		
    		$all[$date] = $date ."-".$date1. "-" . $name . "-" . $des;					
    	}
    	
    	
    	$prev = $k[0];
    	$prev--;
    	$next = $k[0];
    	$next++;	
    	$l = $k[1];
    	if ($prev == 0)
    	{
    	$prev = 12;
    	$l = $k[1] - 1;	
    	}
    	$j = $k[1];
    	if ($next == 13)
    	{
    	$next = 1;
    	$j = $k[1] + 1;
    	}
    	
    	$h = $prev;	
    	switch($h)
    	{
    	case '1': $now = 'February'; break;
    	case '2': $now = 'March'; break;
    	case '3': $now = 'April'; break;
    	case '4': $now = 'May'; break;
    	case '5': $now = 'June'; break;
    	case '6': $now = 'July'; break;
    	case '7': $now = 'August'; break;
    	case '8': $now = 'September'; break;
    	case '9': $now = 'October'; break;
    	case '10': $now = 'November'; break;
    	case '11': $now = 'December'; break;
    	case '12': $now = 'January'; break;
    	}
    //echo "startday is $startday";
    	echo 'Calendar Admin<<  ' . $now . ' - ' .  $k[1] . ' >>Total: ' . $total . '';
    	echo '
    	SMTWTFS';
    		
    	for ($x=1;$x<=$days;$x++)
    	{
    		echo '';
    		$x--;
    		for ($y=1;$y<=7;$y++)
    		{
    			if ($x == 0)
    				$x = 1;
    			$x = $x - $startday+1;
    						
    			if ($x= $days-$startday+1)
    			echo '   ';
    			
    			elseif (empty($all[$x]))
    			echo '' . ($x) . '  ';
    			
    			else
    			{				
    				$cur = explode("-",$all[$x]);
    				//echo ''  . $cur[0] . '' . " $cur[1]$cur[2]" . ' ';
    				echo ''  . $cur[0] . '' . " $cur[1]$cur[2]" . ' ';
    			}	
    			$x = $x + $startday -1;
    			$x++;
    		}
    		echo '';		
    	}
    	echo '';	
    
    ?>
    
  56. I had the problem others reported, where only the last row of the calendar appeared, with only 1 number (last day of month +1) in the little box. To fix it, I did the following:
    1. copied the code & css from the calendar + controls articles
    2. added $events argument to the draw_calendar function
    3. added these lines to the function, after the comment line /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/ and replacing the next line $calendar.= str_repeat(' ',2);

    $event_day = $year.'-'.$month.'-'.$list_day;
    if(isset($events[$event_day])) {
    	foreach($events[$event_day] as $event) {
    		$calendar.= ''.	$event['title'].'';
    	}
    } else {
    	$calendar.= str_repeat(' ',2);
    }
    

    4. I did NOT use the css code from this page. Instead, I altered the css from the calendar+controls article–took out the margin attribute in div.day-number and added valign="top" to the tag a few lines up from the code in step 3 above.

    5. It is critical that your array keys match what the function expects: no zeros in day or month.

    • oh dear. Paste with care. There are line break tags in the block of code. The str_repeat calls should have p-tags and non-breaking spaces. The line inside the foreach block has a div tag with class=”event”. I used code tags; why did the code appear as html?

  57. Alex

    Any update on this, again I’m having the same problem as many others where only the last row of the calendar appeared, with only 1 number (last day of month +1) in the date box.

    Can you help David, seems your codes not working?

  58. Ben

    How do you connect to the database? I’ve created my database:

    CREATE TABLE  `phish3rz_events`.`events` (
    `title` VARCHAR( 255 ) NOT NULL ,
    `event_date` DATE NOT NULL
    ) ENGINE = MYISAM ;
    

    I’ve then included it as in include file, and it connects successfully, but im presented by this error:

    Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/phish3rz/public_html/dev/group/calendar.php on line 91
    cannot get results!
    

    and line 91 is the code:

    $events = array();
    $query = "SELECT title, DATE_FORMAT(event_date,'%Y-%m-%D') AS event_date FROM events WHERE event_date LIKE '$year-$month%'";
    $result = mysql_query($query,$db_link) or die('cannot get results!');     <-- LINE 91!!
    

    Any help would be greatly appreciated.

    • add this to your code

      $db_link = mysql_connect("host","user","pass");
      if (!$db_link)
      {
      die('Could not connect: ' . mysql_error());
      }

    • almost forgot this


      mysql_select_db("DATABASE", $db_link);

      if you want to find any error put

      . mysql_error()

      after

      die('cannot get results!'

  59. @BEN

    you have to define your dblink so heres what i did…

  60. David Hechler

    So I’ve copied and pasted the code straight from the tutorial above. It seems to break. The previous tutorials all work fine on my server, but this tutorial seems to be made up of totally new code and breaks somehow (even when commenting out the database connection bit.

    http://dev.wovenland.com/wp-content/themes/RYFO%202.0/calendar2.php

    • erosuke

      I hv problem like Ben..
      cannot get result,, and then I use method what Daniel said..
      and didn’t change at all.

      Then I change the query into
      $query = “SELECT event FROM event WHERE month(evendate)='”.$month.”‘ AND dayofmonth(eventdate)='”.$list_day[“mday”].”‘ AND year(eventdate)='”.$year.”‘ ORDER BY eventdate”;

      and the result same with David Hechler

      >.<

  61. Zachary

    @David Walsh:
    Thanks David for all the help!

  62. Gavin Adams

    Hi David, thanks for the tutorial, I have managed to get your code to work as soon as I changed DATE_FORMAT(event_date,’%Y-%m-%D’) into DATE_FORMAT(event_date,’%Y-%m-%d’)

    Is there anyway of adding code for events that last more than one day. My table has a event startdate and enddate and I was wondering if anyone has manipulated your code to check for this.

  63. Gavin Adams

    I also added the following code:

    $month = str_pad($month,2,’0′, STR_PAD_LEFT);

    above the line

    $query

  64. Joseph

    My calendar isnt even appearing now after adding the events code in…can someone please take a look at and see what is wrong with the code? thanks

    <?php   
    		mysql_connect("localhost", "root", "") or die(mysql_error());
    		echo "Connected to MySQL";
    		mysql_select_db("events") or die(mysql_error());
    		echo "Connected to Database";
       
            /* draws a calendar */  
            function draw_calendar($month,$year,$events = array()){  
    
            /* draw table */  
            $calendar = '';  
    
            /* table headings */  
            $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');  
            $calendar.= ''.implode('',$headings).'';  
    
            /* 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.= '';  
    
            /* print "blank" days until the first of the current week */  
            for($x = 0; $x < $running_day; $x++):  
                $calendar.= ' ';  
                $days_in_this_week++;  
            endfor;  
       
            /* keep going with days.... */  
    		for($list_day = 1; $list_day <= $days_in_month; $list_day++):
    			$calendar.= '';
    				/* add in the day number */
    				$calendar.= ''.$list_day.'';
          
    				$event_day = $year.'-'.$month.'-'.$list_day;
    				if(isset($events[$event_day])) {
    					foreach($events[$event_day] as $event) {
    						$calendar.= ''.$event['title'].'';
    					}
    				}
    				else {
    					$calendar.= str_repeat(' ',2);
    				}
    			$calendar.= '';
    			if($running_day == 6):
    				$calendar.= '';
    				if(($day_counter+1) != $days_in_month):
    					$calendar.= '';
    				endif;
    				$running_day = -1;
    				$days_in_this_week = 0;
    			endif;
    			$days_in_this_week++; $running_day++; $day_counter++;
    		endfor;
         
    
            // check today day & the current month  
            $calDayClass="calendar-day"; 
            $dayClass="day-number";  
            if ($list_day == date('j') && $month == date('m')) {  
                $dayClass="today"; 
                $calDayClass="today-day"; 
            } 
             
               $calendar.= '';  
                
            /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! **/  
            $calendar.= str_repeat(' ',2);  
            
            $calendar.= '';  
            if($running_day == 6):  
                $calendar.= '';  
            if(($day_counter+1) != $days_in_month):  
                $calendar.= '';  
            endif;  
                $running_day = -1;  
                $days_in_this_week = 0;  
            endif;  
                $days_in_this_week++; $running_day++; $day_counter++;  
    
            /* 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.= ' ';  
                endfor;  
            endif;  
    				
            /* final row */  
            $calendar.= '';  
    
    		/* end the table */  
            $calendar.= '';
    
    		/** DEBUG **/
    		$calendar = str_replace('',''."\n",$calendar);
    		$calendar = str_replace('',''."\n",$calendar);		
        
            /* all done, return result */  
            return $calendar;
    		
    		function random_number() {
    			srand(time());
    			return (rand() % 7);
    		}
    
    		/* date settings */
    		$month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
    		$year = (int)  ($_GET['year'] ? $_GET['year'] : date('Y'));
    
    		/* select month control */
    		$select_month_control = '';
    		for($x = 1; $x <= 12; $x++) {
    			$select_month_control.= ''.date('F',mktime(0,0,0,$x,1,$year)).'';
    		}
    		$select_month_control.= '';
    
    		/* select year control */
    		$year_range = 7;
    		$select_year_control = '';
    		for($x = ($year-floor($year_range/2)); $x <= ($year+floor($year_range/2)); $x++) {
    			$select_year_control.= ''.$x.'';
    		}
    		$select_year_control.= '';
    
    		/* "next month" control */
    		$next_month_link = 'Next Month >>';
    
    		/* "previous month" control */
    		$previous_month_link = '<<   Previous Month';
    
    
    		/* bringing the controls together */
    		$controls = ''.$select_month_control.$select_year_control.'       '.$previous_month_link.'     '.$next_month_link.' ';
    
    		/* get all events for the given month */
    		$events = array();
    		$query = "SELECT title, DATE_FORMAT(event_date,'%Y-%m-%D') AS event_date FROM events WHERE event_date LIKE '$year-$month%'";
    		$result = mysql_query($query,$db_link) or die('cannot get results!');
    		while($row = mysql_fetch_assoc($result)) {
    			$events[$row['event_date']][] = $row;
    		}
    
    		echo ''.date('F',mktime(0,0,0,$month,1,$year)).' '.$year.'';
    		echo ''.$controls.'';
    		echo '';
    		echo draw_calendar($month,$year,$events);
    		echo '';
    		
            /* Current month and year */  
            $year = date ('Y'); $month_title = date ('F');   
            $month_display = date ('n');   
              
            /* sample usages */   
            echo ''.$month_title.' '.$year.'';   
            echo draw_calendar($month_display,$year);
    		}
    ?>
    
  65. ozzy

    Hi, how can i limit my events?for example i only want 5 events on a day and if the user want to add one more there will be message saying “The event is full”, i need ur help plssss!

    • Paige

      @ozzy Did you figure out how to limit the events per day? I tried adding LIMIT 0,7 to the end of the query, but that limited it to 7 per month instead of 7 per day. Any ideas?

  66. Ash

    Hi, I’m having trouble adding the events code to the calender. If someone could show me their database design or their code that would help alot! Thanks in advance guys!

  67. oh my good…i dont know why i can’t display event from january to september…please help me! i have try the givent step above and in comment. this my code:

    /* draws a calendar */
    function draw_calendar($month,$year,$events = array()){
      /* draw table */
      $calendar = '';
    
      /* table headings */
      $headings = array('Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu');
      $calendar.= ''.implode('',$headings).'';
    
      /* 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.= '';
    
      /* print "blank" days until the first of the current week */
      for($x = 0; $x < $running_day; $x++):
        $calendar.= ' ';
        $days_in_this_week++;
      endfor;
    
      /* keep going with days.... */
      for($list_day = 1; $list_day <= $days_in_month; $list_day++):
        $calendar.= '';
          /* add in the day number */
          if($list_day < 10) {
    		$list_day = str_pad($list_day,2,'0', STR_PAD_LEFT);
    		}
    		$calendar.= ''.$list_day.'';
    		
          $event_day = $year.'-'.$month.'-'.$list_day;
          if(isset($events[$event_day])) {
            foreach($events[$event_day] as $event) {
              $calendar.= ''.$event['title'].'';
            }
          }
          else {
            $calendar.= str_repeat(' ',2);
          }
        $calendar.= '';
        if($running_day == 6):
          $calendar.= '';
          if(($day_counter+1) != $days_in_month):
            $calendar.= '';
          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.= ' ';
        endfor;
      endif;
    
      /* final row */
      $calendar.= '';
      
    
      /* end the table */
      $calendar.= '';
    
      /** DEBUG **/
      $calendar = str_replace('',''."\n",$calendar);
      $calendar = str_replace('',''."\n",$calendar);
      
      /* all done, return result */
      return $calendar;
    }
    
    function random_number() {
      srand(time());
      return (rand() % 7);
    }
    
    /* date settings */
    
    $month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
    $year = (int)  ($_GET['year'] ? $_GET['year'] : date('Y'));
    
    /* select month control */
    $select_month_control = '';
    for($x = 1; $x <= 12; $x++) {
    			 if($x < 10) {
    		$x = str_pad($x,2,'0', STR_PAD_LEFT);
    		}
      $select_month_control.= ''.date('F',mktime(0,0,0,$x,1,$year)).'';
    }
    $select_month_control.= '';
    
    /* select year control */
    $year_range = 7;
    $select_year_control = '';
    for($x = ($year-floor($year_range/2)); $x <= ($year+floor($year_range/2)); $x++) {
    
      $select_year_control.= ''.$x.'';
    }
    $select_year_control.= '';
    
    /* "next month" control */
    $next_month_link = 'Bulan Berikutnya >>';
    
    /* "previous month" control */
    $previous_month_link = '<<   Bulan Sebelumnya';
    
    
    /* bringing the controls together */
    $controls = ''.$select_month_control.$select_year_control.'       '.$previous_month_link.'     '.$next_month_link.' ';
    
    $db_link = mysql_connect("localhost","root",""); if (!$db_link) { die('Could not connect: ' . mysql_error()); }
    mysql_select_db("events", $db_link);  
    $events = array();
    $query = "SELECT title, DATE_FORMAT( Tanggal, '%Y-%m-%d' ) AS Tanggal FROM EVENTS WHERE Tanggal LIKE '$year-$month%'";
    $result = mysql_query($query,$db_link) or die('cannot get results!');
    while($row = mysql_fetch_array($result)) {
      $events[$row['Tanggal']][] = $row;
    }
    
    echo ''.date('F',mktime(0,0,0,$month,1,$year)).' '.$year.'';
    echo ''.$controls.'';
    echo '';
    echo draw_calendar($month,$year,$events);
    echo '';
    
  68. 
    /* draws a calendar */
    function draw_calendar($month,$year,$events = array()){
      /* draw table */
      $calendar = '';
    
      /* table headings */
      $headings = array('Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu');
      $calendar.= ''.implode('',$headings).'';
    
      /* 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.= '';
    
      /* print "blank" days until the first of the current week */
      for($x = 0; $x < $running_day; $x++):
        $calendar.= ' ';
        $days_in_this_week++;
      endfor;
    
      /* keep going with days.... */
      for($list_day = 1; $list_day <= $days_in_month; $list_day++):
        $calendar.= '';
          /* add in the day number */
          if($list_day < 10) {
    		$list_day = str_pad($list_day,2,'0', STR_PAD_LEFT);
    		}
    		$calendar.= ''.$list_day.'';
    		
          $event_day = $year.'-'.$month.'-'.$list_day;
          if(isset($events[$event_day])) {
            foreach($events[$event_day] as $event) {
              $calendar.= ''.$event['title'].'';
            }
          }
          else {
            $calendar.= str_repeat(' ',2);
          }
        $calendar.= '';
        if($running_day == 6):
          $calendar.= '';
          if(($day_counter+1) != $days_in_month):
            $calendar.= '';
          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.= ' ';
        endfor;
      endif;
    
      /* final row */
      $calendar.= '';
      
    
      /* end the table */
      $calendar.= '';
    
      /** DEBUG **/
      $calendar = str_replace('',''."\n",$calendar);
      $calendar = str_replace('',''."\n",$calendar);
      
      /* all done, return result */
      return $calendar;
    }
    
    function random_number() {
      srand(time());
      return (rand() % 7);
    }
    
    /* date settings */
    
    $month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
    $year = (int)  ($_GET['year'] ? $_GET['year'] : date('Y'));
    
    /* select month control */
    $select_month_control = '';
    for($x = 1; $x <= 12; $x++) {
    			 if($x < 10) {
    		$x = str_pad($x,2,'0', STR_PAD_LEFT);
    		}
      $select_month_control.= ''.date('F',mktime(0,0,0,$x,1,$year)).'';
    }
    $select_month_control.= '';
    
    /* select year control */
    $year_range = 7;
    $select_year_control = '';
    for($x = ($year-floor($year_range/2)); $x <= ($year+floor($year_range/2)); $x++) {
    
      $select_year_control.= ''.$x.'';
    }
    $select_year_control.= '';
    
    /* "next month" control */
    $next_month_link = 'Bulan Berikutnya >>';
    
    /* "previous month" control */
    $previous_month_link = '<<   Bulan Sebelumnya';
    
    
    /* bringing the controls together */
    $controls = ''.$select_month_control.$select_year_control.'       '.$previous_month_link.'     '.$next_month_link.' ';
    
    $db_link = mysql_connect("localhost","root",""); if (!$db_link) { die('Could not connect: ' . mysql_error()); }
    mysql_select_db("events", $db_link);  
    $events = array();
    $query = "SELECT title, DATE_FORMAT( Tanggal, '%Y-%m-%d' ) AS Tanggal FROM EVENTS WHERE Tanggal LIKE '$year-$month%'";
    $result = mysql_query($query,$db_link) or die('cannot get results!');
    while($row = mysql_fetch_array($result)) {
      $events[$row['Tanggal']][] = $row;
    }
    
    echo ''.date('F',mktime(0,0,0,$month,1,$year)).' '.$year.'';
    echo ''.$controls.'';
    echo '';
    echo draw_calendar($month,$year,$events);
    echo '';
    ?>
  69. Zak

    I still can’t get anything from the db. I did get it to connect, but can’t get anything on the calendar.

  70. Yulia

    Thanks so much for your code! I have combined it with the jquery/ical calendar tutorial to get the event name to show up when you hover over a date, and it’s perfect!

  71. mrugesh shah

    Inspite of reading above comments, I am still not able to display result inside the calendar cell.
    I am able to fetch data successfully and it is showing perfect result outside. but not inside. Will you please help me ?

    following is my code.

    date_default_timezone_set('Asia/Kolkata');
    $tmonth=date("m"); 
    $tyear=date("Y");
    $events = array();
    
        $user_name = "xyz";  /*this is sample data*/
        $password = "********";
        $database = "xyz";
        $server = "abcde";
    
    $db_handle = mysql_connect($server, $user_name, $password);
    $db_found = mysql_select_db($database, $db_handle);
    
    if ($db_found) {
    
    
    /* draws a calendar */
    function draw_calendar($month,$year){
    
      /* draw table */
      $calendar = '';
    
      /* table headings */
      $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
      $calendar.= ''.implode('',$headings).'';
    
      /* 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.= '';
    
      /* print "blank" days until the first of the current week */
      for($x = 0; $x < $running_day; $x++):
        $calendar.= ' ';
        $days_in_this_week++;
      endfor;
    
      /* keep going with days.... */
      for($list_day = 1; $list_day <= $days_in_month; $list_day++):
        $calendar.= '';
          /* add in the day number */
          $calendar.= ''.$list_day.'';
    
    
          /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! **/
    
          $event_day = $year.'-'.$month.'-'.$list_day;
          if(isset($events[$event_day])) {
            foreach($events[$event_day] as $event) {
              $calendar.= $event['tithi'];
            }
          }
          else {
            $calendar.= str_repeat(' ',2);
          }
    
    if(isset($events[$event_day])) { foreach($events[$event_day] as $event) { $calendar.= ''.  $event['title'].''; } } else { $calendar.= str_repeat(' ',2); } 
          
    
          $calendar.= '';
        if($running_day == 6):
          $calendar.= '';
          if(($day_counter+1) != $days_in_month):
            $calendar.= '';
          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.= ' ';
        endfor;
      endif;
    
      /* final row */
      $calendar.= '';
    
      /* end the table */
      $calendar.= '';
      
      /* all done, return result */
      return $calendar;
    }
    
    
    $SQL = "SELECT tithi, DATE_FORMAT(tdate,'%Y-%m-%d') AS tdate FROM date_table where tdate LIKE '$tyear-$tmonth%'";
    $result = mysql_query($SQL);
    
    while ($row = mysql_fetch_assoc($result)) {
       $events[$row['tdate']][] = $row;
    } 
    
    
    /* sample usages */
    echo 'DEC 2011';
    echo draw_calendar(12,2011);
    
    
    mysql_close($db_handle);
    
    }
    else {
    print "Database NOT Found ";
    mysql_close($db_handle);
    }
    
    
  72. Hello,

    I am working on a multi-day event script! i have managed to use your *brilliant* script to display the data in one cell, but how would i use it to show a range? I Have the start & end dates of the event.

    Is it possible? if so, how do i do it?

    Thank you,
    MIhir.

  73. I really like your calendar code and I can see the calendar & the controls but I can’t see the events’ titles at the calendar cells.

    Could you please share another example of working code, just to see if I miss something

    Thanks in advance for your help

    • Sharing my discover:
      I change “D” for a “d” at the array part, but only event dates with two digit appear (10,11,12…) and later I try to change for an “e” and it works

      $events = array();
      $query = "SELECT title, DATE_FORMAT(event_date,'%Y-%m-%e') AS event_date FROM events WHERE event_date LIKE '$year-$month%'";
      $result = mysql_query($query,$db_link) or die('cannot get results!');
      while($row = mysql_fetch_assoc($result)) {
      $events[$row['event_date']][] = $row;
      }

    • lynn Tee

      Thanks Raccoon!! “e” replace “d” for one digit day is works! By the way, what “e” means?

  74. Adam

    Anyone know how to do a mouse over(or click) to show more info? So on the calendar it just shows title, but when you mouse over(or click the title) it shows “where”,”who”, etc?

    • Phil

      Adam, did you ever figure out how to do a mouse over(or click) on the calendar to show more info from that date?

      I’m trying to do this also. Any help would be appreciated!

  75. Sam

    Did anyone figure out how to get it to print dates in the future months?
    I have it printing the name of the person with an appointment, but it refuses to print in future months.

  76. Mike

    Hi. Just stumbled on this site looking for calendar for my community website. I’d like to allow users to pick multiple dates from a calendar if they wish. Sometimes an event, like a play, may be on different unrelated dates, like a Mon, Wed, Sat, etc.

    I’m guessing there would be a popup calendar that would allow them to click on the dates or maybe just having a checkbox if they have multiple events and sending the entry page back with the data filled in already (except date) and then they could choose another date.

    I’m still kicking this around and really don’t know how to go on this project. Any thoughts on this? I’m a little beyond newbie but still learning php, MySQL and can get around a script okay. Was a COBOL programmer analyst for many years, so have an idea of process of a project.

    If anyone knows of a calendar that does this already, I’d appreciate a link so I can take a look. Thanks. And thank you David for the great work on your blog.

  77. Don

    I am a novice and trying to learn html, css, php and mysql.
    I want to create a database with two fields the event and date.
    Could someone explain what the title in the SELECT title below is
    and the FROM events
    This looks like it is talking about three fields title , event_date , and events.
    Any and all greatly appreciated.

    $events = array();
    $query = "SELECT title, DATE_FORMAT(event_date,'%Y-%m-%D') AS event_date FROM events WHERE event_date LIKE '$year-$month%'";
    $result = mysql_query($query,$db_link) or die('cannot get results!');
    while($row = mysql_fetch_assoc($result)) {
    	$events[$row['event_date']][] = $row;
    }
    
    • imjustthiscool

      idk if anyone got back to you or if you need it but on mySQL the table is called “events” with the columns, title and event_date…

      at least that’s what I think, I still have not got my events to show…

  78. felek

    Is there any way to modify the calendar to: not pass events date by mysql but in an array ?
    Like:
    $events = array("2012-02-12"=>"ev1");

  79. Daniel

    @Don
    the mysql query is to get the title, date of the events. this is a EVENT PHP CALENDAR.

  80. GuyWhoFiguredItOut

    The problem could also be in the query,

    In this query:
    “SELECT title, DATE_FORMAT(event_date,’%Y-%m-%d’) AS event_date FROM events WHERE event_date LIKE ‘$year-$month%'”;

    If in the controls, you have chosen a month that has a single value (i.e. March = 3), the first thing that we think is that it comes out as “03” but instead if you echo it out, it goes like “3”. Which is why for months with individual number values (i.e. January, February, March, etc…) you should make sure that the month starts with zero.

  81. cnomann

    So, how would I add a link to an event listing in the calendar? I would like to be able to have the end user click on the link to pull up additional details associated with the event. Here is how I modified the code (approximately line 68):

    $calendar.= ”.’‘ .$event[‘event_name’].’‘;

    The link works, but the id variable is not getting passed to the next page.

    Thanks,

    Connie

  82. cnomann

    sorry code tag needed:


    $calendar.= ''.'• '.'' .$event['event_name'].'';

  83. Where to begin…
    I’ve spent several hours off and on playing with this calendar idea over the last several months. There are so many errors in the code that it has taken weeks for me to sort through it all. Yes I’m a newbie, so I’m not as clear about what I’m doing, that said there are giant holes in what was originally put here.

    I rewrote parts of it, and added some of the suggestions that are in the above comments, and after spending about 6 hours today I finally got data into a working calendar with the code found here
    http://www.codesend.com/view/84dba4acad5998d6fd4119c0c758dc52/

    Now I just have to make it look pretty and get my extra long titles to fit into the calendar spaces.

    John
    March 2012

    • Hey John. Thanks for that script. I was wondering what tables you created to make it work? and if you like to share them with us.

  84. Silver

    Hey John. Thanks for that code. Was wondering what tables you created to make it work and if you ever managed to make it look prettier?

  85. E.R.

    Thanks a million, this is a great resource!
    If anyone wants a quick way to turn the month number into the month name:
    $monthName = date("F", mktime(0, 0, 0, $month, 10));

  86. My calendar is creating an key value array but for some reason the event are not showing up in the calendar and help would be great to get my app working. thanks.

     //connect to the database 
    $username="*******";
    $password="*******";
    $database="*********";
    
    $name="name";
    $start_time="start_time";
    $userid="userid";
    
    $connection = mysql_connect("localhost",$username,$password);
    if (!$connection) {
      die('Could not connect: ' . mysql_error());
     }
    //echo 'Connected successfully';
    
    mysql_select_db($database, $connection) or die( "Unable to select database");
    
    
    
     //set the url for this page                                    
    $my_url = "https://apps.facebook.com/mytown_connect/practice_cal.php";
    
    //require all the other php pages this page requires           
    require_once("mytown_auth.php");
    
    /* draws a calendar */
    function draw_calendar($month,$year,$events){
    
    	/* draw table */
    	$calendar = '';
    
    	/* table headings */
    	$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    	$calendar.= ''.implode('',$headings).'';
    
    	/* 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.= '';
    
    	/* print "blank" days until the first of the current week */
    	for($x = 0; $x < $running_day; $x++):
    		$calendar.= ' ';
    		$days_in_this_week++;
    	endfor;
    
    	/* keep going with days.... */
    	for($list_day = 1; $list_day <= $days_in_month; $list_day++):
    		$calendar.= '';
    			/* add in the day number */
    			$calendar.= ''.$list_day.'';
    			
    			$event_day = $year.'-'.$month.'-'.$list_day;
    			if(isset($events[$event_day])) {
    				foreach($events[$event_day] as $event) {
    					$calendar.= ''.$event['event_name'].'';
    					echo ($event['event_name']);
    				}
    			}
    			else {
    				$calendar.= str_repeat(' ',2);
    			}
    		$calendar.= '';
    		if($running_day == 6):
    			$calendar.= '';
    			if(($day_counter+1) != $days_in_month):
    				$calendar.= '';
    			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.= '&nbsp;';
    		endfor;
    	endif;
    
    	/* final row */
    	$calendar.= '';
    	
    
    	/* end the table */
    	$calendar.= '';
    
    	/** DEBUG **/
    	$calendar = str_replace('',''."\n",$calendar);
    	$calendar = str_replace('',''."\n",$calendar);
    	
    	/* all done, return result */
    	return $calendar;
    }
    
    function random_number() {
    	srand(time());
    	return (rand() % 7);
    }
    
    /* date settings */
    //$month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
    //$year = (int)  ($_GET['year'] ? $_GET['year'] : date('Y'));
    
    /* select month control */
    $select_month_control = '';
    for($x = 1; $x <= 12; $x++) {
    	$select_month_control.= ''.date('F',mktime(0,0,0,$x,1,$year)).'';
    }
    $select_month_control.= '';
    
    /* select year control */
    $year_range = 7;
    $select_year_control = '';
    for($x = ($year-floor($year_range/2)); $x <= ($year+floor($year_range/2)); $x++) {
    	$select_year_control.= ''.$x.'';
    }
    $select_year_control.= '';
    
    /* "next month" control */
    $next_month_link = 'Next Month >>';
    
    /* "previous month" control */
    $previous_month_link = '<< Previous Month';
    ?>
    
    
    <?php
    
    /* bringing the controls together */
    $controls = '  &nbsp'.$select_month_control.$select_year_control.'       '.$previous_month_link.'     '.$next_month_link.' ';
    
    echo $controls;
    ?>
    
    id;
      //echo $fb_user_id;
    $multi_queries = json_encode(array('query1' => 'SELECT eid FROM event_member WHERE uid = me()', 'query2' => 'SELECT eid,  name, start_time FROM event WHERE eid in (SELECT eid FROM #query1)', ));
    
    $results = $facebook->api(array('method' => 'fql.multiquery', 'queries' => $multi_queries));
    //print_r ($results);
    
    foreach ($results[1]['fql_result_set'] as $values)
      {
        $fb_user_id = $user->id;
        //echo $fb_user_id;
        $start_date = date( 'Y-m-d', $values['start_time']);
        $event_name = addslashes($values['name']);
        //$event_name = ($values['name']);
        $eid = ($values['eid']);
        //echo "start date of the event " .$start_date ." The events name ". $event_name ." the eid of the event ".$eid."";
        $mysql_query = "SEE event_id";
        $mysql_query="SELECT * FROM event_id WHERE event_id = $eid";
        $result = mysql_query($mysql_query);
        if(mysql_num_rows($result) == 0) {
          if($fb_user_id != 0) {
    	$sql="INSERT INTO event_id (user_id, event_id, event_name, date_of_event)
    VALUES
    ('$fb_user_id', '$eid', '$event_name', '$start_date')";
    	echo $sql;
          }
          mysql_query($sql) or die("Error: ".mysql_error());
        }
        //mysql_query($sql) or die("Error: ".mysql_error());
      }
    
    
    /* get all events for the given month */
    $events = array();
    if($month < 10) $monthstr = "0".$month; else $monthstr = "".$month;
    $query = "SELECT  DATE_FORMAT(date_of_event,'%Y-%m-%d') AS date_of_event , event_name FROM event_id WHERE date_of_event LIKE '$year-%$monthstr-%'";
    //echo $query;
    $result = mysql_query($query, $connection) or die('cannot get results!');
    while($row = mysql_fetch_array($result)) {
      $events[$row['date_of_event']][] = $row;
      //echo ($events)."";
     }
    while (list($key, $value) = each($events)) {
      echo "Key: $key; Value: $value\n";
     }
    
    
    print_r ($events);
    //echo ''.date('F',mktime(0,0,0,$month,1,$year)).' '.$year.'';
    //echo ''.$controls.'';
    echo '';
    echo draw_calendar($month,$year,$events);
    echo '';
    
  87. Reece Young

    Hi there! I have a calendar script: http://kirkcaldydistrictscouts.org.uk/events.php

    I need help making an admin panel to add events! I have tried but if the event goes on for longer than a day, then the admin updating the calendar has to enter two rows. Is there a way for this not to happen?

    Thanks in advance!

    • Mike B

      Hi reece, i see that on the website you managed to get events working, would you be able to disclose the code? i have tried many different things but not succeeding so far! thanks

  88. Daniel Rantala

    Hi David, and thanks for the awesome piece of code!

    Could someone help me with a little something? I’m certain that this is a piece of cake, but I’m still new to PHP and I can’t solve it myself.

    I’d like to get two calendars on the page: this month, and the next one. So currently it would be first May, then June and all the events added into the calendars.
    I can make the two (for June, I just add +1 to the $month defining, which is in my case the current one) calendars visible and working, but for the next month’s calendar it doesn’t display the events. So, how could I get it to work?

    Thank you very much in advance and best regard,
    Daniel

  89. peter

    I use this code but the title doest display or event does`nt display, please help me.

  90. Arsalan

    my calander doesnt show event.

  91. Daniel

    Would anyone be able to offer an insight into possible ways to add event filters? I reckon it could be done, but then I think as soon as you change the month the filter will reset and i’m not sure what to do about that…

    • Phil

      You might have already worked this out, but I accomplished this by using WHERE, AND, and GROUP BY in the $events array query.

      “SELECT DATE_FORMAT(date_of_event,’%Y-%m-%d’) AS date_of_event , event_name FROM event_id WHERE ** FILTER PARAMETERS HERE ** AND date_of_event LIKE ‘$year-%$monthstr-%'”;

  92. David, and thanks for the awesome piece of code!

    Can someone help me with events that have several days? and that with a start date and end date from a mysql date base.

  93. gary

    can anyone give me the table names in the database.kinda bad in this stuff…

  94. zoro

    Great article thanks. One thing though, chrome is fine but firefox does not accept positioning on table cells so the absolute positioned numbers now end up at the top right of my screen. Any ideas for a fix.

  95. zoro

    OOPS! I just noticed that you have added an extra div with relative positioning to cure this problem.

    Thanks again !

  96. Chris

    I’ve figured out this problem for me, the $month variable is an int (eg January would be 1) and not displaying the month as it would be in mysql as 01. You would need to change things around so 01 was your month variable and not 1.

  97. Ghost

    For those who are having problems with the events not showing in the calendar, edit this part of the latest code:

    $month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
    $year = (int)  ($_GET['year'] ? $_GET['year'] : date('Y'));
    

    …removing the (int) from the $month variable, as it causes the leading zero of the months to disappear.

    • Ghost

      Oh, and add this piece of code after that 2 lines for the provision of the leading zeros when the value of the months are from the drop-down list:


      if($month < 10)
      $month = '0'.$month;

  98. Paige

    Hi all!

    I have implemented the code beautifully and added a “Current Month” button and changed it to fit my table names, etc. but I would like for it to display the persons last name and their appointment time on the calendar instead of the appointment date which is what currently comes up for me. Here is my code… any help would be appreciated!!

    
    <?php
    /* date settings */
    $month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
    $year = (int)  ($_GET['year'] ? $_GET['year'] : date('Y'));
    
    /* select month control */
    $select_month_control = '';
    for($x = 1; $x <= 12; $x++) {
      $select_month_control.= ''.date('F',mktime(0,0,0,$x,1,$year)).'';
    }
    $select_month_control.= '';
    
    /* select year control */
    $year_range = 7;
    $select_year_control = '';
    for($x = ($year-floor($year_range/2)); $x <= ($year+floor($year_range/2)); $x++) {
      $select_year_control.= ''.$x.'';
    }
    $select_year_control.= '';
    
    /* "next month" control */
    $next_month_link = 'Next Month >>';
    
    /* "current month" control */
    $current_month_link = 'Current';
    
    /* "previous month" control */
    $previous_month_link = '<<   Previous Month';
    
    /* bringing the controls together */
    $controls = ''.$select_month_control.$select_year_control.'       '.$previous_month_link.'     '.$current_month_link.'     '.$next_month_link.' ';
    
    
    $db_link = mysql_connect("my_host", "my_username", "my_pw") or die('Cannot connect to the DB');
    mysql_select_db("my_db",$db_link) or die('Cannot select the DB');
    
    $appts = array();
    $query = "SELECT patientprofiles.lastname, appointments.appt_time, appointments.appt_date FROM patientprofiles INNER JOIN appointments ON patientprofiles.patient_id = appointments.patient_id WHERE appt_date LIKE '$year-$month%' ORDER BY appt_time";
    $result = mysql_query($query,$db_link) or die('cannot get results!');
    while($row = mysql_fetch_assoc($result)) {
      $appts[$row['appt_date']][] = $row;
    }
    
    
    /* draws a calendar */
    function draw_calendar($month,$year,$appts){
    
      /* draw table */
      $calendar = '';
    
      /* table headings */
      $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
      $calendar.= ''.implode('',$headings).'';
    
      /* 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.= '';
    
      /* print "blank" days until the first of the current week */
      for($x = 0; $x < $running_day; $x++):
        $calendar.= ' ';
        $days_in_this_week++;
      endfor;
      /* keep going with days.... */
      for($list_day = 1; $list_day <= $days_in_month; $list_day++):
        $calendar.= '';
    	if ($list_day == date('j') && $month == date('m'))
    $calendar.= ''.$list_day.'';
    else
          /* add in the day number */
          $calendar.= ''.$list_day.'';
    	  
    	  $appt_day = $year.'-'.$month.'-'.$list_day;
    	  if(isset($appts[$appt_day])) {
    		foreach($appts[$appt_day] as $appt) {
    			$calendar.=''.$appt['appt_date'].'';	
    		}
    	  }
    
    else {
          /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! **/
          $calendar.= str_repeat(' ',2);
    }
        $calendar.= '';
        if($running_day == 6):
          $calendar.= '';
          if(($day_counter+1) != $days_in_month):
            $calendar.= '';
          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.= ' ';
        endfor;
      endif;
    
      /* final row */
      $calendar.= '';
    
      /* end the table */
      $calendar.= '';
      
      /* all done, return result */
      return $calendar;
    }
    
    ?>
    
    • Paige

      Silly me! I had a typo in my code. All fixed up now :)

  99. Prabha

    @Paige am unable to get output for this dude can u help me..

  100. Tom M

    It’s worth noting that the day format for events is not of the same format called when populating the calendar with events. At first, I was able to call the DB, but no output came back. I recorded my first two records inside of phpMyAdmin, date format YYYY-MM-DD. But, when populating the calendar and conditionally checking for a record for that day, the day format is without the leading 0, so it would only be YYYY-MM-D. This is what I did to fix it.

    /* keep going with days.... */
    for($list_day = 1; $list_day <= $days_in_month; $list_day++):
    $calendar.= '';
    /* add in the day number */
    $calendar.= ''.$list_day.'';
    if ($list_day 10) $event_day = $year.'-'.$month.'-'.$list_day;
    if(isset($events[$event_day])) {
    foreach($events[$event_day] as $event) {
    $calendar.= ''.$event['title'].'';
    }
    }
    else {
    $calendar.= str_repeat(' ',2);
    }

  101. Paige

    I would love it if there were a way to make the day clickable, so that when you click on a day it passes that date in a variable to the next page where you can book an appointment. I currently have a page where you can book an appointment, but you still have to select the date on that page. It would be nice if you could select a day and then have that pull up another page with either a day view calendar so you can see all the events on that day…. or just a way to pass the date information to the next page. Any ideas?

    • Paige

      Just thought I would share… I made the day number clickable so that in theory you could sent the person to a page on which they could create an event for that day. Code below:

       /* add in the day number */
      $calendar.= '
      '.$list_day.'';
      

      I also made the events clickable so that you can go to a page where you could edit that particular event. Code below:

        $event_day = $year.'-'.$month.'-'.$list_day;
      	  if(isset($events[$event_day])) {
      		foreach($events[$event_day] as $appt) {
      			$calendar.=' '.$event['eventt_time'].' - '.$event['lastName'].'';	
      		}
      	  }
      
  102. adam

    Anyway to show the rest of the days in the beginning and end of the weeks, for the previous and next month? show the date and the event?

    • Adam

      I figured this out, I can try and help if anyone needs it.

    • Paige

      Do you mind pasting that section of your code? I would love to add this to my calendar. Thanks!

  103. Paige

    Does anyone know of a way to limit the number off appointments that show up per day in the calendar… and then have a link to more appt’s if there are more than a certain number?

  104. Paige

    AAAA!!!!! Events showing up for January, but not february… WHY!?

    • Paige

      edit: Events are showing up for ALL months EXCEPT February. PLEASE HELP!!!!

    • Nick

      did u ever get this to work? mine only shows events for february and march of any year.

  105. Simone

    guys and girls, pls pls pls help.

    I used the original code and was able to display everything but i also need to display events that span a few days. I tried out the code Sierd gave but it gave an error about the Sql syntax being wrong. I need help. Pls some1.

    P.S. David Walsh: Thank you so much for this. I learned alot.

    • Simone

      I added the following lines but im still not able to display the multiple days spanning event.

      $x = 01;
             $y = 0;
             if(strlen($x) == '1') { $x = $y.$x; }
      	     
      $todaydate = $year.'-'.$month.'-'.$x;
      
      $events = array();
      $query = (" SELECT eventname AS title, startdate AS event_date FROM eventdetails WHERE '$todaydate' >= startdate AND '$todaydate'  '0') 
      		   {
                    while($row = mysql_fetch_array($result))
      			  { 
                    //extract($row); 
      			  $events[$row['event_date']][] = $row;   
      			  }
      		   }
      		   
      		   else { $calendar.= ' '; } 
           	   $x++; 
      
  106. yel

    i can’t display the events on the calendar. :'( how am i supposed to do that? please help.

  107. Hi there! Is there any way to make the starting day Monday instead of sunday?
    Thx!!!

    • KZJ

      Here is the solution for you Joaquin:

      Change these lines:

      $headings = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday');
      	
      $running_day = date('w',mktime(0,0,0,$month,0,$year));
      
  108. David – Just to add my thanks to those of others above for sharing these posts. After following the helpful comments above I managed to get your code to work with my MySQL events table to display a calendar using bootstrap badges to display events. Next thing I would like to try do is display a list of events in a sidebar so I can drag and drop onto the calendar, have seen this in other calendar scripts.

  109. Anu

    Thanks David for this awesome code…

    I am using it in my project to add the shifts of staff in the calendar.
    However, the Shift name(which is the title) does not show up completely, it shows only the first letter of the name.

    My array is
    2013-08-16->Array ( [title] => Two )
    2013-08-17->Array ( [title] => Two )
    2013-08-18->Array ( [title] => Two )
    2013-08-19->Array ( [title] => Two )
    2013-08-25->Array ( [title] => One )
    2013-08-26->Array ( [title] => One )
    2013-08-27->Array ( [title] => One )
    2013-08-28->Array ( [title] => One )

    And the calendar shows only “O” and “T”

    if I change the array to
    2013-08-16->Array ( [title] => Two [event_date] => 2013-08-16 )
    2013-08-17->Array ( [title] => Two [event_date] => 2013-08-17 )
    2013-08-18->Array ( [title] => Two [event_date] => 2013-08-18 )
    2013-08-19->Array ( [title] => Two [event_date] => 2013-08-19 )
    2013-08-25->Array ( [title] => One [event_date] => 2013-08-25 )
    2013-08-26->Array ( [title] => One [event_date] => 2013-08-26 )
    2013-08-27->Array ( [title] => One [event_date] => 2013-08-27 )
    2013-08-28->Array ( [title] => One [event_date] => 2013-08-28 )

    It shows “O2” and “T2” for the corresponding dates.

    Any idea where I might have gone wrong.

    Thank you in Advance

  110. Anu

    Solved:

    I changed line
    $calendar.= ”.$event[‘title’].”;

    to

    $calendar.= ”.$events[$event_day][‘title’].”;

    and now it works as it should, showing the name of the shift.

  111. FUTURE DATES

    Check your SQL statement. I just removed the date clause in my SQL statement and it’s working like a champ.

    • Nick

      Can you be more specific please? i can get it to show for the current month and the past, but not in the future. ty.

  112. RadiationGeek

    Anyone figure out a quick way to highlight todays date??

  113. Steph

    What categories do you have in your database?

  114. Hrt

    I don’t understand this… Why are so many people on here experiencing the same “I-can’t-get-the-events-to-display” problem, while others seem to hit it just fine?

    • imjustthiscool

      Did anyone get back to you about this? Or is this pretty much a dead forum cause I can’t see any events and it’s killing me.

  115. Nick

    can anyone expand on the problem of not showing future events (i can see this month and last months events). on a side note it seems like the font size for the event titles get smaller every time lol. anyone else notice this?

  116. nick

    actually it only shows feb and march 2014 events for me :(

  117. Corey

    Has anyone figured out how to run the event query using SQL instead MYSQL? SQL does not support DATE_FORMAT and I’ve been searching for hours trying to figure out how to get it working on an SQL DB.

    $events = array();
    $query = "SELECT title, DATE_FORMAT(event_date,'%Y-%m-%D') AS event_date FROM events WHERE event_date LIKE '$year-$month%'";
    $result = mssql_query($query,$db_link) or die('cannot get results!');
    while($row = mssql_fetch_assoc($result)) {
    	$events[$row['event_date']][] = $row;
    }
  118. PM

    This is super helpful.. Can someone also help with making the individual event titles in the calendar clickable and have a popup opened up. ?

  119. lyrem

    Can someone help me show the events in the calendar? Here’s my code:

    /* get all events for the given month */
    $events = array();
    $query = "SELECT event_title, DATE_FORMAT(event_start,'%Y-%m-%d') AS event_start FROM calendar_events WHERE event_start LIKE '$year-$month%'";
    $result = mysql_query($query,$db_link) or die('cannot get results!');
    while($row = mysql_fetch_assoc($result)) {
    	$events[$row['event_start']][]= $row;
    }
    

    I don’t know what’s wrong with it.
    Thanks in advance.

  120. cled03

    I have this problem. What is the meaning of this?
    Warning: Illegal string offset ‘event_title’ in C:\xampp\htdocs\cal\cale\cal.php on line 46
    Here’s the code:

    $event_day = $year.'-'.$month.'-'.$list_day;
    		if(isset($events[$event_day])) {
    			foreach($events[$event_day] as $event) {
    				$calendar.= ''.$event['event_title'].'';
    			}
    		}else {
    			$calendar.= str_repeat(' ',2);
    		}				
    		$calendar.= '';
  121. Vin Byori

    Thank you very much! I learned a lot from this. I especially like the if statements in variables :D

  122. Razor

    Wow, what terrible programming. All of this code is a mess.

  123. SHW

    I’ve searched through the comments here but it seems that no one has the problem I have that is… whenever I get to the year 1901 or below the month in the dropdown change all to january, and the days in the calendar don’t change anymore… any suggestions for this ???

  124. Why i can only display the events for the cuurent date?

  125. Karna

    It’s very useful code, but for me it’s connected to DB, but unable to view the events. Can I get full version of the code, pls?

  126. drascom

    dear david thanks you for amazing work.i want to add some info about who cannot print output from sql queries: http://codepen.io/anon/pen/QjKveZ

    with htmlspecialchars($key) you can grab column name
    with htmlspecialchars($field) you can grab values for each records.

  127. drascom
    while($row = mysql_fetch_assoc($result)) {
    	foreach($row as $key => $field) {
    	   $this->calendar.= 'style .'-text">'.htmlspecialchars($field).'' ;
    	}
    }
    
  128. Hi my problem is that i should converter this calendar to one like ical format…

    in the row on my db i will have just the first day of the event and the last, and more events can have the same id,
    I need just 1 and 0 like status

    is it possible editing just few rows of code?

  129. Rhys

    This tutorial makes no sense. All the code seems to be here except for actually adding an event. The are no forms or inputs to do so. Great if you want an image calendar with zero functionality.

    • Christopher Gonzalez

      That’s not true at all haha, if you know even the slightest bit of PHP you only have to code a little bit more to make this work.

      I’ll give you a hint, you must make $db-link actually hold the query for connecting to your sequel server, and you must have a table in your database named events with a row named title that is text and another row named event_date of type date. There is an additional fix for the code in the comments that explains you need to add padding to the month to make events show correctly, but beside that this tutorial is very helpful. And of course, you need to have some method of date selection that inserts dates into this table in your database so that your calendar can pull from it. The last few steps are quite benign compared to coding the calendar from scratch… so be thankful.

      I would know, I have it working perfectly on my site.

  130. Brandon

    How can I get the day to be two digit, like 01, 02, 03, 04, 05, etc…?

  131. Karl

    Hi, first I have to say I love your tutorials. I’ve followed them and made my own little changes and it’s worked so wonderfully for me. I have a question. Do you happen to have anything for the calendar that would show how to…so like I can click a day and input information? So for mine I need it for days off. I’d like to be able to click the day (Say May 28) and have a box appear where I can choose PTO or Bank Hours and then a spot to put description and of course a submit button. But i’m not even sure what to look up.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!