如何对每个表单提交进行$id + 1


how to do $id + 1 with every form submit?

我想添加动态会话变量。所以我从 id=0 开始,但在我提交表格后,id 必须设置为 1,旁边的设置为 2 等。这是我尝试过的。我试图在 if submit 函数中做一个 $id++,但这不起作用。

        <?php
        $id = 0; 
        if (isset($_POST['submit'])) {
            $_SESSION['person'][$id] = array(   
                                                'id' =>  $id,
                                                'voornaam' => $_POST['firstname'], 
                                                'achternaam' => $_POST['lastname'], 
                                                'leeftijd' => $_POST['age'], 
                                                'rol' => $_POST['role'],
                                                'omschrijving' => $_POST['description'],
                                            );
            $id++;
            header('Location: mysite');
        }
    ?>
$id = count($_SESSION['person']);

(假设您已在其他地方将$_SESSION['person']定义为数组。

完整的代码段如下所示:

if (!is_array($_SESSION['person']))
{
    $_SESSION['person'] = array();
}
if (isset($_POST['submit']))
{
    $id                      = count($_SESSION['person']);
    $_SESSION['person'][$id] = array(
        'id'           => $id,
        'voornaam'     => $_POST['firstname'],
        'achternaam'   => $_POST['lastname'],
        'leeftijd'     => $_POST['age'],
        'rol'          => $_POST['role'],
        'omschrijving' => $_POST['description'],
    );
    header('Location: mysite');
}

您实际上并没有在任何地方保留该值。 所以它每次都会重置为 0。

每次您都会创建值:

$id = 0;

然后你递增它:

$id++;

但是你不会把它放在任何地方。 如果该值应遵循用户的会话,请将其保留在会话中。 像这样:

// get the id from session, or create a new one
$id = 0;
if (isset($_SESSION['id'])) {
    $id = $_SESSION['id'];
}
// use the id value in your code
// increment the id and store it back in the session
$_SESSION['id'] = $id + 1;

没有清楚地理解你,但这可能会有所帮助

<?php
    $id = 0; 
    if (isset($_POST['submit'])) {
        $currID = $_SESSION['person']['id'];
        $_SESSION['person'] = array(   
                                    'id' =>  $currID++,
                                    'voornaam' => $_POST['firstname'], 
                                    'achternaam' => $_POST['lastname'], 
                                    'leeftijd' => $_POST['age'], 
                                    'rol' => $_POST['role'],
                                    'omschrijving' => $_POST['description'],
                                );
        header('Location: mysite');
    }
?>