2013-04-05 88 views
0

我有一個猜謎遊戲的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> 

回答

0

您只需使用GET請求或會話將值傳遞給congrats頁面。我建議使用會話,以免人們改變獎金價值。

就修改這部分在這裏:

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

然後(你需要的祝賀頁面更改爲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()。

1

它看起來像你的腳本將工作,但你需要改變congrats.htmlcongrats.php因爲HTML是靜態的和PHP是動態的。你也可能想要使用會話,因爲任何人都可以檢查 - 元素和更改值。