我初始化了$_SESSION variable = 1
,我希望在点击链接时increment/decrements
其值。链接将重新加载页面,然后回显$_SESSION
的值。我使用header()
给了一个提示,但我仍然无法弄清楚如何。
<?php
if (isset($_SESSION['count'])) {
$count = $_SESSION['count'];
} else {
$count = '';
}
?>
<a href="index.php?inc=TRUE">Increment</a>
<a href="index.php?dec=TRUE">Decrement</a>
<?php if (isset($_SESSION['count'])): ?>
<?php echo $count ?>
<?php endif ?>
答案 0 :(得分:1)
header("Location: index.php")
是一个php重定向。在这种情况下,如果上面的代码已经在 index.php 文件中,则无需重定向用户。
<?php
session_start();
if(!isset($_SESSION['count']) { // first time opening the page
$_SESSION['count'] = 0; // initializing the counter
} else { // counter already have a value
if(isset($_GET['inc'])) { // increasing
echo ++$_SESSION['count']; // no need for extra variable (preincrement to echo immediately)
}
if(isset($_GET['dec'])) { // decreasing
echo --$_SESSION['count']; // no need for extra variable (predecrement to echo immediately)
}
}
?>
<a href="index.php?inc=TRUE">Increment</a>
<a href="index.php?dec=TRUE">Decrement</a>
答案 1 :(得分:0)
<?php
session_start();
if(!isset($_SESSION['count'])
$_SESSION['count'] = 0;
$counter = $_SESSION['count'];
$counter = (int)$counter;
if (isset($_GET['inc'])==TRUE) {
$counter++;
$_SESSION['count'] = $counter;
header("Location: index.php");
}
if (isset($_GET['dec'])==TRUE) {
$counter--;
$_SESSION['count'] = $counter;
header("Location: index.php");
}
?>
此外,您可能需要将$ counter转换为int ..