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!
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.
I try your hard work. I am getting nice calendar but itdoesnt print the ecent
sorry spell mistake. it doesn’t print the events?
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
Nice. i will use it for my next proyect, so thanks.
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:
what i do is:
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:
@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:
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:
Hope that helps
WBR
@WBR Thanks,
Interesting, I added it right above the the
$query
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.
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
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
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.
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.
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);
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:
I’ve then included it as in include file, and it connects successfully, but im presented by this error:
and line 91 is the code:
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!'
@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
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!
@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?
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:
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.
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;
}
Thanks Raccoon!! “e” replace “d” for one digit day is works! By the way, what “e” means?
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?
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!
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.
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…
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 script. I was wondering what tables you created to make it work? and if you like to share them with us.
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.
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 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
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
I use this code but the title doest display or event does`nt display, please help me.
my calander doesnt show event.
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…
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-%'”;
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.
can anyone give me the table names in the database.kinda bad in this stuff…
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.
OOPS! I just noticed that you have added an extra div with relative positioning to cure this problem.
Thanks again !
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.
For those who are having problems with the events not showing in the calendar, edit this part of the latest code:
…removing the (int) from the $month variable, as it causes the leading zero of the months to disappear.
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;
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!!
Silly me! I had a typo in my code. All fixed up now :)
@Paige am unable to get output for this dude can u help me..
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);
}
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?
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:
I also made the events clickable so that you can go to a page where you could edit that particular event. Code below:
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?
I figured this out, I can try and help if anyone needs it.
Do you mind pasting that section of your code? I would love to add this to my calendar. Thanks!
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?
AAAA!!!!! Events showing up for January, but not february… WHY!?
edit: Events are showing up for ALL months EXCEPT February. PLEASE HELP!!!!
did u ever get this to work? mine only shows events for february and march of any year.
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.
I added the following lines but im still not able to display the multiple days spanning event.
i can’t display the events on the calendar. :'( how am i supposed to do that? please help.
Hi there! Is there any way to make the starting day Monday instead of sunday?
Thx!!!
Here is the solution for you Joaquin:
Change these lines:
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.
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
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.
FUTURE DATES
Check your SQL statement. I just removed the date clause in my SQL statement and it’s working like a champ.
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.
Anyone figure out a quick way to highlight todays date??
What categories do you have in your database?
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?
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.
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?
actually it only shows feb and march 2014 events for me :(
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.
This is super helpful.. Can someone also help with making the individual event titles in the calendar clickable and have a popup opened up. ?
Can someone help me show the events in the calendar? Here’s my code:
I don’t know what’s wrong with it.
Thanks in advance.
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:
Thank you very much! I learned a lot from this. I especially like the if statements in variables :D
Wow, what terrible programming. All of this code is a mess.
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 ???
Why i can only display the events for the cuurent date?
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?
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 namewith
htmlspecialchars($field)
you can grab values for each records.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?
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.
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 namedevents
with a row namedtitle
that is text and another row namedevent_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.
How can I get the day to be two digit, like 01, 02, 03, 04, 05, etc…?
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.