每个表单提交怎么做$ id + 1?

时间:2015-01-26 15:14:08

标签: php forms session 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');
        }
    ?>

3 个答案:

答案 0 :(得分:1)

$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');
}

答案 1 :(得分:0)

你实际上并没有在任何地方坚持这个价值。所以它每次都会重置为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;

答案 2 :(得分:0)

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

<?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');
    }
?>