重新访问页面时恢复单选按钮选择

时间:2012-01-14 23:33:36

标签: php session radio-button session-variables

我有一个PHP脚本,允许用户通过选择与学生成绩相对应的单选按钮来输入成绩。它允许他们在最终提交之前查看所选等级。我还希望页面能够返回选择页面并记住所选择的单选按钮,这样用户在返回时不必再次设置所有这些按钮。这是我到目前为止编码的内容,它将用户带回选择页面但不恢复单选按钮选择。

<?php

session_start();

$script_name = $_SERVER["PHP_SELF"];

if(!isset($_SESSION["course"]) || !isset($_SESSION["course"])) {
    $_SESSION["course"] = $_POST["coursename"];
    $_SESSION["section"] = $_POST["section"];
}

if(($_SESSION["authenticated"] == true || isset($_POST["back"])) && !isset($_POST["continue"])) {

    $course = $_SESSION["course"];
    $section = $_SESSION["section"];
    $file_name = $course.$section.".txt";
    $_SESSION["filename"] = $file_name;

    // Open file containing student names.
    $fp = fopen($_SESSION["filename"], "r") or die("Could not open file");
    $students = array();
    $i = 0;

    echo "<h2>Grades Submission Form</h2>";
    echo "<h2>Course: $course, Section: $section</h2>";
    echo "<form action=\"$script_name\" method='post'>";
    echo "<table border='1'>";
    while (!feof($fp)) {
        $line = trim(fgets($fp));
        $students[$i++] = $line;

        echo "<tr><td>$line</td>";
        echo "<td><input type='radio' name=\"$line\" value='A'/>A</td>";
        echo "<td><input type='radio' name=\"$line\" value='B'/>B</td>";
        echo "<td><input type='radio' name=\"$line\" value='C'/>C</td>";
        echo "<td><input type='radio' name=\"$line\" value='D'/>D</td>";
        echo "<td><input type='radio' name=\"$line\" value='F'/>F</td>";
        echo "</tr>";
    }
    echo "</table><br>";
    echo "<input type='submit' name='continue'/>";
    echo "</form>";

} elseif($_SESSION["authenticated"] == true && isset($_POST["continue"]) && !isset($_POST["back"])) {

    unset($_POST["continue"]);
    $keys = array_keys($_POST);
    $values = array_values($_POST);

    echo "<h2>Grades to Submit</h2>";
    echo "<table border='1'>";
    echo "<tr><th>Name</th><th>Grade</th></tr>";
    for($i = 0; $i < count($keys); $i++) {
        echo "<tr><td>{$keys[$i]}</td><td>{$values[$i]}</td></tr>";
    }
    echo "</table><br>";

    echo "<form action='confirmation.php' method='post'>";
    echo "<input type='submit' value='Submit Grades'/>";
    echo "</form>";

    echo "<form action=\"$script_name\" method='post'>";
    echo "<input type='submit' value='Back'/>";
    echo "</form>";

} else {
    header("Location: main.php");
}
?>

1 个答案:

答案 0 :(得分:1)

您可以serialize()包含单选按钮的数组,并将其存储在会话中。当你回去时,你所要做的就是反序列化并重新设置数据。