我已经开始为一个关于生物的游戏编写一个PHP脚本,有4个是/否的问题,我想要做的是编写一个函数,显示2个按钮,表示是和否,然后给每个不同的名字我运行该函数的时间,例如yes1和no1,然后在下次运行该函数时,按钮的名称将为yes2和no2。
我已经尝试过这样做但是它工作不正常,下面是我到目前为止所做的代码,任何帮助都会非常感激。
<?php
session_set_cookie_params(2592000);
session_start();
?>
<html>
<head>
<title>Creature Guessing Game</title>
</head>
<body>
<h1>Creature Guessing Game</h1>
<p> Welcome to the creature guessing game! </p>
<p>Click the button below to start or restart the game </p>
<form method="post" action="Creatures.php">
<input type="submit" name="start" value="Start Game" />
</form>
<?php
$questions = array('Does the creature live on land?', 'Does it have wings?', 'Does it live near water?', 'Can it fly?');
function repeat()
{
$number = 0;
$number++;
echo "<form method ='post' action='Creatures.php'>
<input type='submit' name='yes'.$number value='Yes' />
<input type='submit' name='no'.$number value='No' />
</form>";
}
//If form not submitted, display form.
if (!isset($_POST['start'])){
?>
<?php
} //If form is submitted, process input
else{
switch($_POST)
{
case yes1:
echo $questions[0];
repeat();
break;
case no1:
echo $questions[1];
repeat();
break;
case yes2:
echo $questions[2];
repeat();
break;
case no2:
$questions[3];
repeat();
}
}
?>
</body>
</html>
答案 0 :(得分:5)
为此,您需要在请求之间保持状态。
function repeat() {
$number = $_SESSION['number'];
$number++;
echo "<form method ='post' action='Creatures.php'>
<input type='submit' name='answer' value='Yes' />
<input type='submit' name='answer' value='No' />
</form>";
$_SESSION['number'] = $number;
}
开关
if($_POST['answer']=='Yes') {
switch($_SESSION['number']) {
case 1:
break;
case 2:
break;
}
} else {
switch($_SESSION['number']) {
case 1:
break;
case 2:
break;
}
}
答案 1 :(得分:4)
我不同意接受的答案: 在没有会话的情况下,这是一种更简单的方法:
function repeat() {
static $number = 0;
$number++;
echo "<form method ='post' action='Creatures.php'>
<input type='submit' name='answer' value='Yes' />
<input type='submit' name='answer' value='No' />
</form>";
}
答案 2 :(得分:0)
您必须在会话中存储“号码”,因为每次提交页面时都会丢失其值。