将值附加到变量

时间:2018-02-12 15:56:41

标签: php

希望有人能引导我朝着正确的方向前进。我有一个带有输入字段和按钮的表单。填充输入字段并单击按钮时,字段的值将显示在变量$ capture_numbers中。

我希望能够添加到该值,即人输入1,$ capture_numbers显示1,人输入2,$ capture_numbers现在显示1,2,人输入3,$ capture_numbers现在显示1,2,3等上。我正在考虑存储前一个值并附加到它但是无法弄清楚它是如何完成的。下面是我的脚本。

    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <fieldset>
           <input type="text" name="mynumbers[]">
           <button>add another numbers</button>
           <input type="submit" value="Submit" title="submit">
        </fieldset>
    </form>

    <?php
         if(isset($_POST['mynumbers']) && is_array($_POST["mynumbers"])) {
            $capture_numbers = ' ';
            foreach($_POST["mynumbers"] as $key => $value) {
                $capture_numbers .= $value .", ";
            }
            echo $capture_numbers;
         }
    ?>

1 个答案:

答案 0 :(得分:0)

您需要一些持久存储来存储以前的提交。有效选项包括数据库,本地存储,cookie,会话等。

在这个例子中,我使用了session。提交表单时,检查会话以查找以前的条目,然后将新的表单附加到列表中。我在代码中添加了评论。

修改:您不需要将文本字段添加为数组。 IE浏览器。名称=&#34;通过myNumbers []&#34 ;.这通常用于当您有多个具有相同名称的输入并希望将它们作为数组读取时。

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    <fieldset>
        <input type="text" name="number">
        <button>add another numbers</button>
        <input type="submit" value="Submit" title="submit">
    </fieldset>
</form>

<?php
// Start the session
session_start();

// Check if form is submitted
if (!empty($_POST)) {

    // Create a variable to store all numbers
    $allNumbers = [];

    // Does the session contain anything
    if (isset($_SESSION['previous'])) {
        // Grab it from the session as an array and store it
        $allNumbers = explode(',', $_SESSION['previous']);
    }

    // Append the new number to the list
    $allNumbers[] = $_POST['number'];

    // Convert it to a comma separated string
    $capture_numbers = implode(',', $allNumbers);

    // Store the entire list in the session
    $_SESSION['previous'] = $capture_numbers;

    // Output the result
    echo $capture_numbers;
}
相关问题