PHP doesn't do calculations inside strings and doesn't parse PHP tags inside strings. You are already in 'PHP mode', and opening another PHP tag inside the string just outputs that tag as you may have noticed when you inspected the link in your browser.
Instead, try closing the string, concatenating the next/previous month (using the dot operator), and concatenating the last part of the link:
//previous and next links
echo "<a href='calendar.php?month=" . ($month-1) . "'>Previous</a>";
echo "<a href='calendar.php?month=" . ($month+1) . "'>Next</a>";
You can also calculate the values into variables first, because simple variables can be used inside double-quoted strings:
//previous and next links
$previousMonth = $month-1;
$nextMonth = $month+1;
echo "<a href='calendar.php?month=$previousMonth'>Previous</a>";
echo "<a href='calendar.php?month=$nextMonth'>Next</a>";
On the first request, you may not have a month at all, so you may want to check for that too, for instance using isset.
$month = 1;
if (isset($_GET['month'])) {
$month = (int)$_GET['month'];
}
As you can see, I already did an (int) typecast there too. Combining this with the variables version, allows you to make the code a little more solid by performing some checks on the input, and only output the previous/next links if they make sense.
$month = 1;
if (isset($_GET['month'])) {
$month = (int)$_GET['month'];
}
if ($month < 1 || $month > 12) {
// Invalid month. You can choose to throw an exception, or just
// ignore it and use a default, like this;
$month = 1;
}
//previous and next links, if necessary.
$previousMonth = $month-1;
$nextMonth = $month+1;
if ($previousMonth >= 0) {
echo "<a href='calendar.php?month=$previousMonth'>Previous</a>";
}
if ($nextMonth <= 12) {
echo "<a href='calendar.php?month=$nextMonth'>Next</a>";
}
Oh, and a minor detail. Personally I don't like to put 'big' chunks of HTML inside a string, so I'd rather use some template, or at least write it like this. As you can see, you can close and open PHP tags (just not inside strings), so you can output plain HTML from within your PHP code. The <?= $x ?>
notation is a shorthand for <? echo $x; ?>
.
//previous and next links, if necessary.
$previousMonth = $month-1;
$nextMonth = $month+1;
if ($previousMonth >= 0) {?>
<a href='calendar.php?month=<?=$previousMonth?>'>Previous</a>
<?php}
if ($nextMonth <= 12) {?>
<a href='calendar.php?month=<?=$nextMonth?>'>Next</a>
<?}