So I have currently used this http://davidwalsh.name/php-calendar as my calendar, but I am having trouble coming up with a way to add a 'next'/'previous' link to the next month... any help is greatly appreciated!
Since the function to draw the calender is
function draw_calendar($month,$year){
you have to supply $month
and $year
in the next/previous links, e.g.
/calendar.php?month=12&year=2011
This data is then available in $_GET
when such a link is clicked. You dont want unsanitized data, so you fetch it like this on top of your calendar script:
$input = filter_input_array(
INPUT_GET,
array(
'month' => array(
'filter' => FILTER_VALIDATE_INT,
'options' => array('min_range' => 1, 'max_range' => 12)
),
'year' => array(
'filter' => FILTER_VALIDATE_INT,
'options' => array('min_range' => 2010, 'max_range' => 2015)
)
)
);
The filter function will make sure we get a month between 1 and 12 and a year between 2010 and 2015 (adjust accordingly or remove the options as you see fit). If the passed numbers are not in that range (or no link was clicked yet), we will get false
for them, which means we will have to set sane defaults, e.g.
$input['year'] = $input['year'] ?: date('Y');
$input['month'] = $input['month'] ?: date('n');
This will either use the valid values passed to the script or, in case of invalid values, set the year and/or month to the current year and/or month.
Now draw the calendar:
echo draw_calendar($input['month'], $input['year']);
For the next/previous link you can either manually check whether the month is at 12 or 1 and then increase/decrease the year accordingly or use a DateTime
object
$dateTime = new DateTime;
$dateTime->setDate($input['year'], $input['month'], 1));
printf(
'<a href="/calendar.php?month=%d&year=%d">Next</a>' .
'<a href="/calendar.php?month=%d&year=%d">Previous</a>',
$dateTime->modify('-1 month')->format('n'),
$dateTime->format('Y'),
$dateTime->modify('+2 month')->format('n'),
$dateTime->format('Y')
);
Another option would be to store the current month and year in a session and then just have next/previous links without year and month but rather just something like +1 and -1 to go back and forth. But then you have no direct way to jump to a certain month.
And that's all there is to it.