0

我正在尝试了解如何使用 PHP 会话,因为我需要在我正在制作的另一个网站上实现它们。无论如何,我已经制作了一个非常基本的表格,上面有 3 个问题,当您回答一个问题然后离开网页时,它会记住您之前提出的问题。

会话部分有效,问题是问题显示两次,当您转到下一个问题时,上一个答案如下所示,如果您想了解我的意思,请转到简单表单会话

有谁知道我可以如何更改它,以便一次只显示 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>
4

1 回答 1

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 语句。试试这种方式。

于 2012-06-01T11:34:28.120 回答