簡體   English   中英

祝賀頁面未顯示猜數字游戲中的變量

[英]Congratulation page not showing the variable from the number-guessing game

我有一個數字游戲的php腳本和一個祝賀頁面的html腳本。 如果猜對了,游戲將結束,並打開祝賀頁面。 在php中,我有一個變量$ prize = 1000-100 * $ _POST ['tries'],這樣,如果第一個猜測正確,玩家將贏得$ 1000; 如果玩家有第二個猜測,則獎金將減少$ 100,依此類推。 此變量以$ _POST ['prize']的形式保存在php的隱藏字段中。 我希望最終的獎項可以印在祝賀頁面上,但是沒有按我預期的那樣工作。 我在html中做錯了什么嗎? 謝謝大家,瑪麗亞。

guess.php:

<?php
if(isset($_POST['number'])) {
   $num = $_POST['number'];
} else {
   $num = rand(1,10);
}
if(isset($_POST['prize'])) {
   $prize =1000-100 * $_POST['tries'];
} else {
   $prize = 900;
}
$tries=(isset($_POST['guess'])) ? $_POST['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) {
    header("Location: Congrats.html");
    exit;
} 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; ?>"/><br/>
<input type="hidden" name="number" value="<?php echo $num; ?>"/><br/>
<input type="hidden" name="prize" value="<?php echo $prize; ?>"/>
</p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>

congrats.html:

<! DOCTYPE html>
<html>
<header>
<title>Congratulation!</title>
<body>Congratulation!<br/>
You Won <?php echo $_POST['prize']; ?> dollars!
</body>
</header>
</html>

看來您的腳本可以工作,但是您需要將congrats.html更改為congrats.php因為html是靜態的,而php是動態的。 另外,您可能想使用會話,因為任何人都可以檢查元素並更改值。

您只需要使用GET請求或會話將值傳遞到祝賀頁面。 我建議您使用會議,這樣人們就不能更改獎金價值。

只需在此處修改此部分:

} elseif ($_POST['guess']==$num) {
    $_SESSION['prize'] = $_POST['prize'];
    header("Location: Congrats.php");
    exit;
}

然后(您需要將congrats頁面更改為php頁面以使用會話btw啟用php)

Congrats.php

<! DOCTYPE html>
<html>
<header>
<title>Congratulation!</title>
<body>Congratulation!<br/>
You Won <?php echo $_SESSION['prize']; ?> dollars!
</body>
</header>
</html>

PS:會話還將在兩個文檔的頂部都需要session_start()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM