user1292857
user1292857

Reputation: 27

How to stop adding a number when it reaches its limit

<?php
    session_start();


        if(isset($_POST['sessionNum'])){
            //Declare my counter for the first time

            $_SESSION['initial_count'] = $_POST['sessionNum'];
            $_SESSION['sessionNum'] = $_POST['sessionNum'];

    }

    if(!isset($_SESSION['sessionCount'])){
         $_SESSION['sessionCount'] = 1;
    }
    else
    {
         $_SESSION['sessionCount']++;
    }

$sessionMinus =  $_SESSION['sessionCount'];


?>

How do I get it so that if $_SESSION['sessionCount'] is less than $_SESSION['sessionNum'], then add 1 to $_SESSION['sessionCount'] and if it equals $_SESSION['sessionNum'], then stop adding 1 to $_SESSION['sessionCount']?

Also if I go back on a previous page and I go back onto this page, I want $sessionMinus to go back to '1', and finally if the user refreshes the page, then whatever number $sessionMinus is, keep it on that number when page refreshes.

Upvotes: 0

Views: 91

Answers (2)

Jon
Jon

Reputation: 437336

How do I get it so that if $_SESSION['sessionCount'] is less than $_SESSION['sessionNum'], then add 1 to $_SESSION['sessionCount'] and if it equals $_SESSION['sessionNum'], then stop adding 1 to $_SESSION['sessionCount']?

if (!isset($_SESSION['sessionCount'])) {
    $_SESSION['sessionCount'] = 1;
}
else if ($_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
    ++$_SESSION['sessionCount'];
}

Also if I go back on a previous page and I go back onto this page, I want $sessionMinus to go back to '1'

To do that you have to set $_SESSION['sessionMinus'] (or some other variable) in the previous page. Once this page is reached, the only way to know what happened earlier is specifically through $_SESSION variables. You cannot detect it on the spot.

and finally if the user refreshes the page, then whatever number $sessionMinus is, keep it on that number when page refreshes.

This is not possible. You cannot tell if the page was refreshed or loaded from scratch¹. What you could do is use the PRG pattern and count the "P" page as "the user just got here" and the "G" page as "the user has refreshed the page". You can set a variable (e.g. $_SESSION['redirecting'] = true) from the "P" page and modify it on the "G" page ($_SESSION['redirecting'] = false); just before you do that, check if it was true to begin with. If it was, then the user is here due to your redirect (which will only happen once). If it was already false, they have refreshed the page.


¹You can try to do it, again through $_SESSION, but really you are just guessing. There is no way to know for certain.

Upvotes: 1

peipst9lker
peipst9lker

Reputation: 605

if ($_SESSION['sessionCount'] < $_SESSION['sessionNum']) { 
    // sessionNum is bigger then sessionCount
    $_SESSION['sessionCount']++; 
}

Upvotes: 0

Related Questions