2014-02-08 80 views
0

我對PHP的知識非常有限,並會感謝任何幫助。如何使用PHP將表單值傳遞到多個頁面?

我想創建一個PHP測驗,其中每個問題在不同的頁面上。在第三頁上,對第一頁和第二頁的答案進行評分和計算。問題是我只得到最後一個答案的分數(從第二頁開始)

我試圖使用會話,但可能會搞砸了一些東西。此外,我不使用數據庫。

在第一頁(q1.php)我有這種形式

<form action="q2.php" method="post"><li> 
    <h3>Koji ste pol?</h3> 

    <div> 
    <input type='radio' name='answer1' id='answer1' value='A' /> 
    <label for='answer1A'>Muško</label> 
    </div> 

    <div> 
    <input type='radio' name='answer1' id='answer1' value='B' /> 
    <label for='answer1B'>Žensko</label> 
    </div> 
    </li><input type="submit" value="posalji" /></form> 

在第二頁(q2.php)我有這樣的代碼

<?php 
session_start(); 
$_SESSION['answer1'] = $_POST['answer1']; 
?> 

<form action="rezultat.php" method="post"><li> 
    <h3>Da li ste zaposleni?</h3> 

    <div> 
    <input type='radio' name='answer2' id='answer2' value='A' /> 
    <label for='answer2A'>Da</label> 
    </div> 

    <div> 
    <input type='radio' name='answer2' id='answer2' value='B' /> 
    <label for='answer2B'>Ne</label> 
    </div> 
    </li><input type="submit" value="posalji" /></form> 

而對第三頁(rezultat.php)需要計算第1頁和第2頁的答案

<?php 
session_start(); 
$_SESSION['answer1'] = $_POST['answer1']; 
$_SESSION['answer2'] = $_POST['answer2']; 
?> 

Vaš rezultat je: 

<?php 
$answer1= $_POST['answer1']; 
$answer2= $_POST['answer2']; 

$score = 0; 

if ($answer1 == "A"){$score += 5;} 
if ($answer1 == "B"){$score += 4;} 

if ($answer2 == "A"){$score += 1;} 
if ($answer2 == "B"){$score += 5;} 

echo "$score"; ?> 

請幫忙,提前謝謝。

回答

4

在您第三頁(rezultat.php),應刪除這一行:

$_SESSION['answer1'] = $_POST['answer1'];

它不再需要爲你已經從第二頁上的分配值$_SESSION['answer1'](q2.php )。你當前做的是對$_SESSION['answer1']因爲$_POST['answer1']第二頁(q2.php)根本不存在分配值。

然後替換此:

$answer1= $_POST['answer1']; 
$answer2= $_POST['answer2']; 

$answer1= $_SESSION['answer1']; 
$answer2= $_SESSION['answer2']; 

您可能需要將其分配給$_SESSION之前,您$_POST添加一些驗證層。

0
$_POST['answer1']; 

在rezultat.php上不可用,所以現在你用不存在的POST數據覆蓋答案。 之前閱讀$ _ POST []字段,運行快速檢查,看看它的實際可用

if(isset($_POST['answer1'])){} 

這將給予你一個線索,ANSWER1不可用最終PAE。

0

「answer1」字段在第二頁(q2.php)中不可用,所以您不能使用$ _POST ['answer1']。

使用下面的修正腳本!

 <?php 
     session_start(); 
     $_SESSION['answer2'] = $_POST['answer2']; 
    ?> 

    Vaš rezultat je: 

    <?php 
    $answer1= $_SESSION['answer1']; 
    $answer2= $_SESSION['answer2']; 

    $score = 0; 

    if ($answer1 == "A"){$score += 5;} 
    if ($answer1 == "B"){$score += 4;} 

    if ($answer2 == "A"){$score += 1;} 
    if ($answer2 == "B"){$score += 5;} 

    echo "$score"; ?> 
相關問題