我正在尝试理解如何使用PHP会话,因为我需要在我正在制作的另一个网站上实现它们。无论如何,我已经制作了一个非常基本的表格,上面有3个问题,当你回答问题然后离开网页时,它会记住你之前的问题。
会话部分有效,问题是问题显示两次,当你转到下一个问题时,如果你想看看我的意思,请转到Simple Form Sessions
有没有人知道如何更改它以便它一次只显示1个问题并且会话仍然有效,此时如果我取出所有会话代码,它可以正常工作。这是我到目前为止所有的代码。
<?php
session_set_cookie_params(2592000); //Sets cookie to last for 30 days
session_start();
?>
<html>
<head>
<title> Using Sessions with Buttons </title>
</head>
<body>
<p> This is the start</p>
<form method='POST' action='SessionButtons.php'>
<input type='submit' name='start' value='start' />
</form>
<?php
$q1 = 'This is question 1';
$q2 = 'This is the second question';
$q3 = 'This is question, number 3';
$answer1 = "This is the first answer";
$answer2 = "This is the answer to the second question";
$answer3 = "Third answer, this is ";
$answer4 = "This is the mighty fourth answer";
$start = "<form method='POST' action='SessionButtons.php'>
<input type='submit' name='yes1' value='yes' />
<input type='submit' name='no1' value='no' />
</form>";
$form1 = "<form method='POST' action='SessionButtons.php'>
<input type='submit' name='yes2' value='yes' />
<input type='submit' name='no2' value='no' />
</form>";
$form2 = "<form method='POST' action='SessionButtons.php'>
<input type='submit' name='yes3' value='yes' />
<input type='submit' name='no3' value='no' />
</form>";
if (!isset($_POST['start'])){
if (isset($_SESSION['question'])){
echo $_SESSION['question'];
echo $_SESSION['form'];
}
} //If start button has been pressed, display questions
else
{
echo $q1;
echo $start;
}
if ($_POST['yes1']){
echo $q2;
echo $form1;
$_SESSION['question'] = $q2;
$_SESSION['form'] = $form1;
}
if ($_POST['no1']){
echo $q3;
echo $form2;
$_SESSION['question'] = $q3;
$_SESSION['form'] = $form2;
}
if ($_POST['yes2']){
echo $answer1;
$_SESSION['answer'] = $answer1;
}
if ($_POST['no2']){
echo $answer2;
$_SESSION['answer'] = $answer2;
}
if ($_POST['yes3']){
echo $answer3;
$_SESSION['answer'] = $answer3;
}
if ($_POST['no3']){
echo $answer4;
$_SESSION['answer'] = $answer4;
}
?>
</body>
</html>
答案 0 :(得分:0)
只需要对您的代码进行部分解释
if (!isset($_POST['start'])){
if (isset($_SESSION['question']) && $_POST['yes1'] && $_POST['no1']){
echo $_SESSION['question'];
echo $_SESSION['form'];
}
} //If start button has been pressed, display questions
else
{
echo $q1;
echo $start;
}
if ($_POST['yes1']){
echo $q2;
echo $form1;
$_SESSION['question'] = $q2;
$_SESSION['form'] = $form1;
}
如果您有问题,请重新调整我的代码以跳过第二个if语句。试试这种方式。