Add Events to the PHP Calendar
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"> </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> </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"> </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 >></a>';
/* "previous month" control */
$previous_month_link = '<a href="?month='.($month != 1 ? $month - 1 : 12).'&year='.($month != 1 ? $year : $year - 1).'" class="control"><< Previous Month</a>';
/* bringing the controls together */
$controls = '<form method="get">'.$select_month_control.$select_year_control.' <input type="submit" name="submit" value="Go" /> '.$previous_month_link.' '.$next_month_link.' </form>';
/* 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 '<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!
Comments
Be Heard!
Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!
Thanks for the tutorial, this is a great resource for web developers just starting out!
One more great tutorial!!! Thanks David
Good tutorial. If only this would’ve been released 2 weeks ago. I was still working on a calendar bases project back then. :P
Good tut,
I think there is a bud at line 115
$events[$row['event_date']] = $row;
Should be:
$events[$row['event_date']][]= $row;
Right on SiTo — updated.
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.
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
Thanks David.
Can you write an article about how to add events using php/mysql/ajax (hopefully with jquery)? Plz plz plz?
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
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;
}
oh sorry, i change the name of the time column from event_date to time
I have the DB built, but can’t get the two connected. Any ideas on how to connect the two?
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?
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.
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 …
@William Rouse: Try this:
$month = str_pad($month,2,’0′, STR_PAD_LEFT);
@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.
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.
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.
@William Rouse: I’ve updated my post. Try setting the date format in the SQL query to “%Y-%m-%D”
@David Walsh:
‘%Y-%m-%d this works for me.
“%Y-%m-%D” attaches English suffix like st, nd …
Thanks for the weekend work.
WBR
@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.
@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.
@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?
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
@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.
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
I still can’t get anything from the db. I did get it to connect, but can’t get anything on the calendar.
http://simnar.com/calendar200.php?month=1&year=2010 A link to look at.
@William Rouse: Outstanding, adding it to the second location got me going. Thanks again William.
@William Rouse:
Yes, thanks for your help as well. Everything seems to be working!
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?
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.
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?
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
@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?
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.
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.
Any ideas what I’m doing wrong here? I can’t get the events into the calendar.
In my DB I have two test events, here’s the format: 2010-12-17 00:00:00
include (“../req/session.php”);
$db_link = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(‘Cannot connect to the DB’);
mysql_select_db(DB_NAME,$db_link) or die(‘Cannot select the DB’);
/* 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.’
‘;
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;
$event_day = $year.’-’.$month.’-’.$list_day;
if(isset($events[$event_day])) {
foreach($events[$event_day] as $event) {
$calendar.= ”.$event['title'].’
‘;
}
}
/** DEBUG **/
$calendar = str_replace(”,”.”\n”,$calendar);
$calendar = str_replace(”,”.”\n”,$calendar);
/* final row */
$calendar.= ‘
‘;
/* end the table */
$calendar.= ‘
‘;
/* all done, return result */
return $calendar;
}
function random_number() {
srand(time());
return (rand() % 7);
}
/* date settings */
$month = (int) str_pad(($_GET['month'] ? $_GET['month'] : date(‘m’)),2,”0″, STR_PAD_LEFT);
$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.’
‘;
echo ‘
/* calendar */
body{font-size:12px;}
table.calendar{ border-left:1px solid #999;position:relative;margin:0 auto;}
td.calendar-day { height:80px;min-height:80px; font-size:11px; position:relative; }
td.calendar-day-np{ background:#eee; min-height:80px; }
th.calendar-day-head{ background:#ccc; font-weight:bold; text-align:center; width:120px; padding:5px; border-bottom:1px solid #999; border-top:1px solid #999; border-right:1px solid #999; }
div.day-number{ background:#999; padding:5px; color:#fff; font-weight:bold; float:right; margin:0px; width:20px;height:10px; text-align:center;}
/* shared */
td.calendar-day, td.calendar-day-np { width:120px; border-bottom:1px solid #999; border-right:1px solid #999;}
#controls{margin:0 auto;text-align:center;}
#controls #date{display:inline;margin:0;padding:0;}
‘;
echo ”.date(‘F’,mktime(0,0,0,$month,1,$year)).’ ‘.$year.”;
echo ”.$controls.”;
echo ”;
echo draw_calendar($month,$year,$events);
echo ”;
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/
@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?
@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.
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.
Hay Guys,
how can i change the month to germany or any lang?
I have now implementet this calendar on my site, but i doesn’t show the dates, it only shows the 32′th.
Any suggestions?
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 …
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!
@waspinator:
I’m having the same output. Any solutions?
@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…
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’.
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?
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.
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.
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
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.
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!
I want its database structure also.. can u help me??
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.
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?
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 ”;
?>
Unavailable
Booked
Available
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?
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?
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!'
hey
Thank You for the piece of code……okay have some doubts firstly i haven’t understood the query and i’ve created a table with just two field one is description[varchar100] and the other is date[Date]….now all i want is my particular event stored under description to be show in the calendar, using your piece of code haven’t made any changes except for the query(Select * from mytable) but gives me an error….
can someone help please!
~`God Bless`~
@BEN
you have to define your dblink so heres what i did…
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
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
>.<
@David Walsh:
Thanks David for all the help!
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.
I also added the following code:
$month = str_pad($month,2,’0′, STR_PAD_LEFT);
above the line
$query
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]
<?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);
}
?>
[/php]
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!
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!
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:
<?php
/* 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 ”;
?>
<?php/* 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 '';
?>
I still can’t get anything from the db. I did get it to connect, but can’t get anything on the calendar.
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!
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.
<?php
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);
}
?>
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.
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;
}
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?
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.
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.
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;
}
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");@Don
the mysql query is to get the title, date of the events. this is a EVENT PHP CALENDAR.
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.
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
sorry code tag needed:
$calendar.= ''.'• '.'' .$event['event_name'].'';
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 code. Was wondering what tables you created to make it work and if you ever managed to make it look prettier?
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));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.
<?php
//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.= ' ';
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 = '  '.$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 '';
?>
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!
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