Kara
Kara

Reputation: 11

My counter is edited correctly when a button is clicked but this new value is not saved for the next action

When a button is clicked my counter should be lowered by 1 or 2 depending on the clicked button. This works the first time but when a button is clicked again the original value of my counter is used to make this second calculation rather then the result of the previous calculation. I don't understand why this new value is not being saved.

This is my code;

<?php
// luciferSpel.php

declare(strict_types=1);

session_start();

if(!isset($_SESSION["lucifer"])) { 
   $_SESSION["lucifers"] = array_fill(0,7,"lucifer");
   $_SESSION["teller"] = 6;
}


if (isset($_GET['reset']) && $_GET['reset'] == 1) { 
    unset($_SESSION["lucifers"]); 
    unset($_SESSION["teller"]);
    header("Location: " .$_SERVER["PHP_SELF"]);
    exit;
}

$lucifers = &$_SESSION["lucifers"];
$teller = &$_SESSION["teller"];

if (isset($_POST["min1"]) && $teller >= 0) {
    unset($lucifers[$teller]);
    $teller --;
}

if (isset($_POST["min2"]) && $teller >=1) {
    unset($lucifers[$teller],$lucifers[$teller-1]);
    $teller -= 2;
}

if ($teller === -1) {
    header("Location: luciferSpelAfgelopen.php ");
    exit;
}

?>

<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8>
<title>Luciferspel</title>
</head>
<body>
    <h1>Luciferspel</h1>
    <?php echo $teller; echo count($lucifers) ?>
        <?php for ($f=0; $f < count($lucifers); $f++) :?>
                <img src="img/lucifer.png" alt="lucifer" />     
            <?php endfor; ?>
    <form method="post">
            <button type="submit" name="min1">Een lucifer wegnemen
            </button> 
            <button type="submit" name="min2">Twee lucifers wegnemen
            </button>
    </form>
    <p>Klik <a href="?reset=1" >hier</a> om een nieuw spel te starten.</p>
</body>
</html>

I tried several variation on this code where the counter is saved differently, b.e. after every calculation (&$_SESSION["teller"]=$teller). But the result of the calculation is never saved to start the next calculation with. It always resets to the original setting of 6.

Upvotes: 1

Views: 32

Answers (0)

Related Questions