0

下面的 PHP 脚本用于猜数游戏。隐藏字段用于存储猜测次数,由变量 $tries 表示。不管我怎么尝试,猜测的次数($tries)永远不会增加。有人可以告诉我代码有什么问题吗?玛丽亚

<?php
$num=21;
$tries=(isset($_POST['guess'])) ? $tries+1: 0;
if (!isset($_POST['guess'])) {
    $message="Welcome to the Guessing Game!";
} elseif (!is_numeric($_POST['guess'])) {
    $message="You need to type in a number.";
} elseif ($_POST['guess']==$num) {
    $message="You WON 1 million point!";
} elseif ($_POST['guess']>$num) {
    $message="Try a smaller number";
} else {
    $message="Try a bigger number";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p><strong>Guess number: </strong><?php echo $tries; ?></p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p><label for="guess">Type your guess here:</label><br/>
<input type="text" id="guess" name="guess" />
<input type="hidden" name="tries" value="<?php echo $tries; ?>"/></p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
4

2 回答 2

3

改变:

$tries=(isset($_POST['guess'])) ? $tries+1: 0;

到:

$tries=(isset($_POST['tries'])) ? $_POST['tries']+1: 0;

或者,根据条件,仅在存在猜测时增加,然后:

$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;

但是基于这样做guess将允许该人通过不输入数字来重置计数器;)

于 2013-04-02T02:49:28.103 回答
0

$tries当您尝试增加它时未定义。但是它可以在$_POST

$tries=(isset($_POST['guess'])) ? $tries+1: 0;
// Change to
$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;
于 2013-04-02T02:50:04.903 回答