Search code examples
phpdatepaginationplanning

Change var value with link


I have do a custom page with a planning of the actual week, and the week is defined by the today's day.

I need to put link for previous and next week, and i want to make a link to reopen my page with today'day + 7 (for next) or -7 (for previous).

This is the function for defined days of the week with the today's day var.

So i need to make a link in the page to go on previous week (same page with $today -7) and another to go on next week (same page with $today +7).

Can you help me ? thanks a lot.

EDIT : I have try to adapt the Michal's solution and delete my old poo function for replace procedural code :

<?php 

date_default_timezone_set('Europe/Paris');

if (!empty($_GET['today'])) 
{
    $today = $_GET['today'];
}

else
{
    $today = Date('y-m-d'); 
}

$todayMinus7 = Date('y-m-d', strtotime("-7 days")); //set variable to last week (-7 days)
$todayPlus7 = Date('y-m-d', strtotime("+7 days"));  //set variable to next week (+7 days)


$my_date = $today; 
$week = date("W", strtotime($my_date)); // get week
$y =    date("Y", strtotime($my_date)); // get year

$first_date =  date('y-m-d',strtotime($y."W".$week)); //first date 
$second_date = date("y-m-d",strtotime("+1 day", strtotime($first_date)));

?>

<a href="get_day.php?today=<?php echo $todayPlus7; ?>">A Week Ago</a>

<?php   echo $first_date;  ?>

RESULT :

Now when i load the page i got the first_date (monday) 18/10/08, thats ok !

if i press on the link i have the next monday 18/10/15, thats's ok !

But if i click on the link once again (for go on next week of the previous next week) nothing changes (always 18/10/15 instead of 18/10/22).

Do you an idea for solve the problem ?

Thanks a lot,


Solution

  • I have something similar on my page, I have created different variables with dates and then just use them whenever I need to... So create:

    <?php
    $todayMinus7 = Date('y-m-d', strtotime("-7 days")); //set variable to last week (-7 days)
    $today = Date('y-m-d');                             //set variable to today
    $todayPlus7 = Date('y-m-d', strtotime("+7 days"));  //set variable to next week (+7 days)
    $dayName = !empty($_GET['today']) ? date('l',$_GET['today']) : date('l',$today); ; //shorthand for IF today is set, get day name
    ?>
    

    Then have you links where you need them and add above variable to the links like so:

    <a href="get_day.php?today=<?php echo $todayPlus7.'">'.$dayName;?></a>