Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Add Controls to the PHP Calendar

50 Responses »
PHP / XHTML / CSS Calendar

I showed you how to create a PHP calendar last week. The post was very popular so I wanted to follow it up with another post about how you can add controls to the calendar. After all, you don't want your users to need to wait until the next month to see events outside of the current month, right? Now we'll add "Next Month", "Previous Month", and month/year dropdown controls to the calendar.

The PHP => HTML

/* 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>';

echo $controls;

I wont explain the code because it's boring and simple but you may be wondering why I didn't include the controls within the PHP function. Since you may or may not want the controls and will want to style them differently, placing the controls within the PHP function would be a bad idea.

Can you think of any other controls to add to the calendar? How about an AJAX method? Share them!

Discussion

  1. July 20, 2009 @ 8:31 am

    http://davidwalsh.name/dw-content/php-calendar-controls.php?month=2147483648&year=2147483647
    That is the maximum date that can be generated from your scripts. Maybe it will show an epoch-like bug in 2147483647-2009=2.147.481.638 years from now.. xD

  2. ahmed
    July 20, 2009 @ 8:54 am

    You should have it highlight “today” :)

  3. July 20, 2009 @ 8:58 am

    @Alex: I could set up a min/max for year values, but I’ll let people like you do your worst :)

    @Ahmed: Good idea. Once I get some more ideas, I’ll revise the post with all of them included.

  4. July 20, 2009 @ 9:19 am

    You are about 12 hours too late! XD
    Maybe we should all hook up on some big open source calendar class project, or something…

  5. July 20, 2009 @ 9:21 am

    @Chris the Developer: Sorry :D

  6. ahmed
    July 23, 2009 @ 11:24 pm

    How about custom time zones too?

  7. August 2, 2009 @ 8:02 am

    Very nice Calendar I’m just gonna repeat the same question as Ahmed did, highlight Todays date.

    Zed

  8. September 5, 2009 @ 3:47 am

    How about ading events to the calander?

  9. September 6, 2009 @ 4:56 pm

    Nice script. Will be using and giving credit for this one…

    Many thanks

    @ all the ones that requested Hilighting todays sate I did it by changing the following code

    /* keep going with days…. */
    for($list_day = 1; $list_day <= $days_in_month; $list_day++):
    $calendar.= ‘<td class=”calendar-day”>’;

    /* add in the day number */
    $calendar.= ‘<div class=”day-number”>’.$list_day.’</div>’;

    /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
    $calendar.= str_repeat(‘<p> </p>’,2);

    $calendar.= ‘</td>’;

    TO

    /* keep going with days…. /
    for($list_day = 1; $list_day <= $days_in_month; $list_day++):
    $calendar.= ”;
    /
    Add Jimmy Hack Highlight Today /
    if($list_day == date(‘d’) && $month == date(‘n’) && $year == date(‘Y’))
    {
    $calendar.= ”.$list_day.”;
    }
    else
    {
    /
    add in the day number /
    $calendar.= ”.$list_day.”;
    }
    /
    * QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
    $calendar.= str_repeat(‘ ‘,2);

    $calendar.= ‘</td>’;

    And adding a new item in the CSS for DIV.day-today

    Hope that helps, its probbabley not the best way of doing it, but it seems to work!

    Jimmy

  10. September 10, 2009 @ 12:20 am

    Nice script, simple to the point, great addition to the first part.
    The only things I could think to add would be maybe some sweet functionality to throw a day into a modal to display all of the events on the day, or to pass data to ajax a model for a more in-depth description of the event or data set.

    also on Jimmy’s code block, unless I am missing something there seems to be something missing from his second code block…
    but the basics is as follows… compare todays date to the one in cycle, if they match modify the class name.


    /* keep going with days…. /
    for($list_day = 1; $list_day <= $days_in_month; $list_day++):
    $className = ($list_day == date(’d’) && $month == date(’n’) && $year == date(’Y’)) “highlightToday”: “calendar-day”;
    $calendar.= ”; //quotes spaced for detail, do not include
    /
    add in the day number */

    //where you would add a class to the css to modify the color of the cell to what you want…

  11. November 9, 2009 @ 1:37 am

    heeii.. how about adding event to calendar?

  12. gav
    December 8, 2009 @ 4:35 am

    Hi guys – great examples just wondered if you provided downloadable archives of the examples?
    thanks again :-)

  13. gav
    December 8, 2009 @ 5:06 am

    Another way to highlight the current date, not the smallest amount of code possible but I just made it nice & simple to read for less experienced php guys & gals :-)

    Feel free to give me constructive criticism i’m still learning myself :-)

    // check today day & the current month
    if ($list_day == date(‘j’) && $month == date(‘m’))
    $calendar.= ”.$list_day.”;
    else
    $calendar.= ”.$list_day.”;

    /** add to css block **/
    div.today { color: red !important; }

  14. gav
    December 8, 2009 @ 5:38 am

    Just noticed it does something weird in Internet Explorer 8 (haven’t tried IE6 or 7) works fine in Chrome/Firefox though – On my website it displays the calendar fine, however on my local LAMP development machine it doesn’t – it is the exact same code so cannot see why it would be doing this any ideas? (See the screenshow below)

    http://www.gavk.co.uk/calendar/calendar.png

    Note – if I refresh the page it then loads fine, however when I click ‘Previous’ or ‘Next’ month it goes back to the weird unformatted style.

    Am I doing something really dumb here any responses would be appreciated (but nothin mean lol) ;-)

    Thanks

  15. gav
    December 8, 2009 @ 5:49 am

    Sorry guys if it feels like I am spamming this!!

    Ignore the last question – I must have been having a ‘blonde’ moment – the CSS should have been above the table, I must need more sleep :-)

    Thanks again David – this is a really impressive blog! Keep it up! :-D

  16. gav
    December 8, 2009 @ 11:45 am

    Hi Guys – Last comment I promise!

    Nothing special but some have mentioned having ‘events’ integrated into the calendar, i’ve done some ‘basic’ that grabs events from a mysql DB using the adodb library (note the database stuff is only on my local testing machine not the site URL below as of yet).

    http://gavk.co.uk/calendar/calendar-v1.php

    I’ve used the jQuery Tools library to do the overlay effect – if this of any use to anyone I can provide the PHP files if anyone wishes so you can play around with it further.
    It’s good to give something back for once :-)

    Awesome blog David keep it going!

  17. gav
    December 9, 2009 @ 11:04 am

    Hi guys,

    I’ve been playing around with this example recently and just wondered the best approach for events that span multiple days?

    I got a decent demo working that pulls date via the DB for single dates and displays them but cannot work out the best approach for an event that will for example start on 5th Dec & end on the 8th Dec – ideally i’d want this to show this event appear for times, the 5th, 6th, 7th & 8th days of the calendar.

    Anyone have any suggestions?

  18. pankaja
    December 12, 2009 @ 3:50 am

    @Gav :

    hey bro it’s really helpfull for us if you can send us the PHP codes. we are stuk with an assignment. :((
    Thanks

    @Gav:

  19. gav
    December 14, 2009 @ 10:24 am

    Hi Pankaja – bit busy with a project myself too at the minute – I will at some put these files up with some commenting – as my code is looking very bloated now – while it works it is confusing even when I look at it lol :-)

    At some point i’ll upload these somewhere then you can feel free to modify & hopefully improve upon my attempt as i’m no expert (unlike Mr D.Walsh!) :-)

  20. william rouse
    December 17, 2009 @ 2:35 pm

    David:
    Is there a place where the code for the first two parts, the calender and the controls, are linked together. If not can you show me how to integrate them.
    Thanks
    WBR

  21. gary
    January 4, 2010 @ 12:49 pm

    This is what I am looking for, but like WIlliam I am not sure where to put the code for the controls.. Where would it go?

  22. gary
    January 4, 2010 @ 2:12 pm

    I just cant get the controls to work. Not sure where the colde goes.

  23. gav
    January 4, 2010 @ 2:25 pm

    @William, Gary..

    Just put the controls at the top of the page within the tags – give me a shout if your unsure…

  24. william rouse
    January 4, 2010 @ 2:55 pm

    Oooh! I got it working!
    Thanks!

  25. gary
    January 4, 2010 @ 3:04 pm

    William… Where did you put the code?

  26. william rouse
    January 4, 2010 @ 3:17 pm

    In my code it ended up after the random number function.
    [code]

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

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

  27. gary
    January 4, 2010 @ 3:25 pm

    I am so new to this. However I don’t even have a function random_number.

  28. william rouse
    January 4, 2010 @ 3:33 pm

    Gary:
    I would send you the code I have, but I don’t want to publish my email. One alternative for you is to view the source of the demo, and edit it down to see the relevant parts.

  29. gary
    January 4, 2010 @ 3:36 pm

    That’s okay. I am sure I will figure it out. @William Rouse:

  30. gary
    January 5, 2010 @ 7:56 am

    @William Rouse:

    William, if you are still willing to share the code here is my email. gary@ssdgn.com thanks in advnace for the help.

  31. gary
    January 5, 2010 @ 4:36 pm

    Thank you William. Now I have to figure out how to connect it to the database in order to add the events. Way over my head, but I am learning.

  32. harol
    January 13, 2010 @ 7:00 pm

    Hey Gav, William or Gary can you send me the code? i am having the same problem and i also want to be able to show the events on the calendar itself.
    Thanks for your help. harolfuentes@yahoo.com

  33. gav
    January 14, 2010 @ 4:05 am

    Hi Harol – I will try and get this for you on the weekend and illustrate how I have done the events – the way that I have done it is not the best method but does the job. Will sort this out for you in a couple of days just mega-busy at the minute..

  34. william rouse
    January 14, 2010 @ 4:12 am

    @Gav:
    Can you take a look at the highlight for the current day also. I see it in the CSS but not in the code.
    Thanks
    WBR

  35. gav
    January 14, 2010 @ 4:19 am

    @William
    No worries highlighting the current day is fairly simple – will point that out for u as well.

  36. harol
    January 14, 2010 @ 4:26 pm

    @Gav and William,

    Look forward to the updates, thanks for alll your help.

  37. gav
    January 17, 2010 @ 4:40 pm

    Hi guys – not sure how exactly I missed this before but there is another article by David Walsh with doing the events here.. well worth a read, looks easier than my method as I required events spanning multiple days, months etc..

    http://davidwalsh.name/php-event-calendar

    As for setting the current day try this..
    /* $today variable will be set to ‘today’ or EMPTY depending on the date matching the current date */

    $today = ($list_day == date(‘j’) && $month == date(‘m’) && $year == date(‘Y’)) ? ‘ today’ : ”;

    Then when you loop through each day in the calendar when we hit the current day it will print the string ‘today’ – you could put this into something like event stuff…

    Long day so not the best explanation I know! Let me know if that doesn’t make sense i’ll give you another heads-up with it.
    Gav
    then i’d just create a css class called ‘today’ and maybe change colour, font-weight etc…

  38. william rouse
    January 17, 2010 @ 9:21 pm

    @Gav: Well after 3 readings it doesn’t make sense and the line of code seems to have syntax errors, so help the lame, and show where in the code you placed this.
    WBR

  39. gav
    January 18, 2010 @ 4:17 am

    @William: I will try and simplify what I have done as it uses something called ‘adodb’ for getting stuff via a database which will probably confuse the hell out of you :-)

  40. william rouse
    January 18, 2010 @ 4:40 am

    Yeah, you are right, if this is from the old ActiveX Data Object, I have not seen that since I worked on C++ with a Borland compiler. Yikes!

  41. gav
    January 18, 2010 @ 4:46 am

    It isn’t that bad lol – I’ve just used this for the database stuff
    http://phplens.com/adodb/reference.varibles.adodb_fetch_mode.html & used object orientated programming to ‘seperate’ everything into objects, really useful once you get your head around OOP.

    Will simplify for you soon :)

  42. david
    February 4, 2010 @ 10:27 am

    echo $controls

    to see the controls….

  43. david
    February 4, 2010 @ 10:27 am

    sorry

    echo $controls;

  44. cindy
    April 11, 2010 @ 10:25 am

    There’s a slight issue with the calendar function when the last day of the month is the last day of the week (e.g. July 2010), where an extra row of days is generated.

    The fix is shown in the following code snippet:

    /* 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 !! **/
    $calendar.= str_repeat(‘ ’,2);

    $calendar.= ”;
    if($running_day == 6):
    $calendar.= ”;
    if(($day_counter+1) != $days_in_month):
    $calendar.= ”;
    $days_in_this_week = 0;
    endif;
    $running_day = -1;
    // $days_in_this_week = 0;
    endif;
    $days_in_this_week++; $running_day++; $day_counter++;
    endfor;

  45. william rouse
    April 12, 2010 @ 9:30 am

    @Cindy:
    I found the error you described about July 2010 in my version of the code also.
    In trying to update my code, I found syntax errors in your example:
    $calendar.= ‘’;
    This produces a syntax error for me.
    Would you be able to post your entire file somewhere for inspection?
    Thanks!
    WBR

  46. bo gunnarson
    May 20, 2010 @ 3:12 am

    Hello and thank you for some very good tutorials.
    I have only one question, i’m a bit new on programming in php, and i wondering how to get the controls to act with the calendag?

    Thanks in advance.

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!