每次提交表单时都防止重新创建数组

时间:2014-07-02 16:08:35

标签: php arrays forms session

我试图在3个不同的数组中存储和显示来自表单的会话数据,每次提交表单时都会更新数组。第一次提交表单时,阵列数据会正确显示,但每次都会重新显示,而不是将新值推送到数组。

我相信每次提交表单时都会重新创建数组,但我不知道如何防止这种情况。新手程序员在这里非常感谢任何帮助。

<!DOCTYPE HTML>
<?php session_start(); ?>

<html>
<head>
    <title> Populating Arrays from User </title>
</head>
<body>

<?php   
// Create the three arrays
    $teamsports = $solosports = $favteam = array(); 
// Create variables to hold each value
    $team = $solo = $country = "";
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Team Sport: <input type="text" name="team"><br><br>
    Solo Sport: <input type="text" name="solo"><br><br>
    Fav Team: <select name="country">
        <option value="Canada">Canada</option>
        <option value="Canada">USA</option>
        <option value="England">England</option>
        <option value="Germany">Germany</option>
    </select><br><br>
    <input type="submit" name="submit" value="Click to submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $_SESSION["team"] = $_POST["team"];
    $_SESSION["solo"] = $_POST["solo"];
    $_SESSION["country"] = $_POST["country"];

    array_push($teamsports, $_SESSION["team"]);
    array_push($solosports, $_SESSION["solo"]);
    array_push($favteam, $_SESSION["country"]); 
}
?>

<h2> Results </h2><br>
Team Sports:<?php foreach ($teamsports as $value) {echo $value;}?><br><br>
Solo Sports:<?php foreach ($solosports as $value) {echo $value;}?><br><br>
Fav Teams:<?php foreach ($favteam as $value) {echo $value;}?><br><br>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

Josh是对的,阵列被覆盖了。我相信这可能更符合您的要求:

<!DOCTYPE HTML>
<?php session_start(); ?>

<html>
<head>
    <title> Populating Arrays from User </title>
</head>
<body>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Team Sport: <input type="text" name="team"><br><br>
    Solo Sport: <input type="text" name="solo"><br><br>
    Fav Team: <select name="country">
        <option value="Canada">Canada</option>
        <option value="Canada">USA</option>
        <option value="England">England</option>
        <option value="Germany">Germany</option>
    </select><br><br>
    <input type="submit" name="submit" value="Click to submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $_SESSION["team"][] = $_POST["team"];
    $_SESSION["solo"][] = $_POST["solo"];
    $_SESSION["country"][] = $_POST["country"];
}
?>

<h2> Results </h2><br>
Team Sports:<?php foreach ($_SESSION["team"] as $value) {echo $value;}?><br><br>
Solo Sports:<?php foreach ($_SESSION["solo"] as $value) {echo $value;}?><br><br>
Fav Teams:<?php foreach ($_SESSION["country"] as $value) {echo $value;}?><br><br>

</body>
</html>

答案 1 :(得分:0)

只要页面加载,您的PHP数组就会存在。当您发布新表单时,页面将重新加载并吹走阵列。您需要将该数组数据保留在会话中。