Genalb Bajrami
Genalb Bajrami

Reputation: 41

Pushing buttons to increase or decrease the same value

I want to increase the value when i push the first button and if i push the second button to decrease the same value.Here is my code:

    <?php

    session_start();

    if (isset($_POST['btn1'])) {
        $_SESSION['clicks'] += 1 ;
        echo  $_SESSION['clicks'];
    } 

    else { if(isset($_POST['btn2'])){

        $_SESSION['click'] = $_SESSION['clicks'] + ($_SESSION['click']- 1) ;
        echo  $_SESSION['click'];
    }
    }
     ?>
   <br><br><br><br>
    <form action="" method="post">
    <input type="submit" name="btn1" value="+1">
    <input type="submit" name="btn2" value="-1">
    </form>

Upvotes: 0

Views: 350

Answers (2)

Phright
Phright

Reputation: 179

Make sure you declare the session variable if it's empty. The reason I changed your code slightly in my example is because it allows the button value to change the variable, which means you don't need to have the if else and it also means that, should you want to, it can be expanded by adding new buttons, such as +2 or -2 without having to change any of the php code, making it more maintainable. Also be careful to use the same variable names. I tend to copy/paste them after first use to cut down on typing mistakes.

<?php
session_start();

if(! empty($_POST)) {

    if(empty($_SESSION['click'])) {

        $_SESSION['click'] = 0;
    }

    $_SESSION['click'] += $_POST['btn'];
}

print $_SESSION['click'];
?>

<form action="" method="post">
<input type="submit" name="btn" value="+1">
<input type="submit" name="btn" value="-1">
</form>

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33813

You need to ensure the session is set once before trying to add/subtract from it and use the same session name clicks rather than click for the subtract I guess.

<?php

    session_start();
    if( !isset( $_SESSION['clicks'] ) ) $_SESSION['clicks']=0;

    if( isset( $_POST['btn1'] ) ) {
        $_SESSION['clicks']++;
    } elseif( isset( $_POST['btn2'] ) ){
        $_SESSION['clicks']--;
    }
    echo 'clicks: '. $_SESSION['clicks'];
?>




<form action="" method="post">
    <input type="submit" name="btn1" value="+1">
    <input type="submit" name="btn2" value="-1">
</form>

Upvotes: 2

Related Questions