我想创建一个投放骰子的php网站,然后计算每次获得它的次数。
但是php中的变量没有正确增加,我在这里做错了什么?
这就是我现在所拥有的:
<form action="" method="get">
<input type="submit" value="Kast en terning" name="kastTerning"/>
</form>
<?php
session_start();
$_SESSION["terning1"] = 0;
$_SESSION["terning2"] = 0;
$_SESSION["terning3"] = 0;
$_SESSION["terning4"] = 0;
$_SESSION["terning5"] = 0;
$_SESSION["terning6"] = 0;
function oppgave5() {
if (isset($_GET["kastTerning"])) {
$roll = rand(1, 6);
if ($roll == 1) {
$_SESSION["terning1"] ++;
} elseif ($roll == 2) {
$_SESSION["terning2"] ++;
} elseif ($roll == 3) {
$_SESSION["terning3"] ++;
} elseif ($roll == 4) {
$_SESSION["terning4"] ++;
} elseif ($roll == 5) {
$_SESSION["terning5"] ++;
} elseif ($roll == 6) {
$_SESSION["terning6"] ++;
}
}
return $roll;
}
oppgave5();
echo "Du kastet " .oppgave5() ."</br>";
echo "1 kom " . $_SESSION["terning1"] . " ganger.</br>";
echo "2 kom " . $_SESSION["terning2"] . " ganger.</br>";
echo "3 kom " . $_SESSION["terning3"] . " ganger.</br>";
echo "4 kom " . $_SESSION["terning4"] . " ganger.</br>";
echo "5 kom " . $_SESSION["terning5"] . " ganger.</br>";
echo "6 kom " . $_SESSION["terning6"] . " ganger.</br>";
?>
答案 0 :(得分:0)
更改
$_SESSION["terning1"] = 0;
$_SESSION["terning2"] = 0;
$_SESSION["terning3"] = 0;
$_SESSION["terning4"] = 0;
$_SESSION["terning5"] = 0;
$_SESSION["terning6"] = 0;
到
// set them to 0 only when you start a new session.
if (!isset($_SESSION["terning1"], $_SESSION["terning2"], $_SESSION["terning3"], $_SESSION["terning4"], $_SESSION["terning5"], $_SESSION["terning6"])) {
$_SESSION["terning1"] = $_SESSION["terning2"] = $_SESSION["terning3"] = $_SESSION["terning4"] = $_SESSION["terning5"] = $_SESSION["terning6"] = 0;
}
否则,每次重新加载页面时,都会将其设置为0
。