Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable increment based on a check box being checked or not in PHP

Tags:

checkbox

php

I have got two requirements for the code snippet below.

  • The var is to be incremented when I click the check box. - Done

  • The var should save the previous number if the check box is not checked. - Not Done

Currently it changes back to 1 if you do not check the check box for var.

The code snippet:

if (isset($_POST['var'])) { 
    $var = $var + 1; 
} else { 
    $var = $_POST['var']; 
}
like image 631
user3416665 Avatar asked Dec 01 '25 02:12

user3416665


1 Answers

You could consider using session variables for your purpose.

Firstly, you may start the new session like this:

session_start();

Then, you could do the thing you desire in the following manner:

// Initialize $_SESSION['var'], if needed
if(!isset($_SESSION['var'])) {

    $_SESSION['var'] = 0;   

}

if (isset($_POST['var'])) {

    // Increment the var
    $var = $_SESSION['var'] + 1; 

    // Save the var as a session variable
    $_SESSION['var'] = $var;

} else { 

    // Restore the var from the session variable
    $var = $_SESSION['var']; 

}

Also, at some point you might want to destroy a session data. It is performed as following in PHP:

session_destroy();

Please take into account the fact that good practices of using PHP sessions is a completely separate question for which you could google.

Click for some more sandbox-level info on PHP Sessions.

UPD: Here is a full PHP / HTML code for a working example of what you are looking for:

<?php session_start(); ?>
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form method="POST">
            Increment $var <input type="checkbox" name="var" value="var">
            <input type="submit" value="Submit">
        </form>
        <p>
            <?php

            // Initialize $_SESSION['var'], if needed
            if(!isset($_SESSION['var'])) {
                $_SESSION['var'] = 0;       
            }

            if (isset($_POST['var'])) {
                // Increment the var
                $var = $_SESSION['var'] + 1; 
                // Save the var as a session variable
                $_SESSION['var'] = $var;
            } else { 
                // Restore the var from the session variable
                $var = $_SESSION['var']; 
            }

            echo $var;

            ?>
        </p>
    </body>
</html>

Please let me know whether it helps or not.

like image 72
dnl-blkv Avatar answered Dec 02 '25 16:12

dnl-blkv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!