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


Restore radio button selection when revisiting a page

我有一个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");
}
?>

您可以序列化()一个包含单选按钮状态的数组,并将其存储在会话中。当您返回时,您所要做的就是取消它的序列化并重新设置数据。