dounangshen6553 2014-01-09 09:17
浏览 82
已采纳

将表单变量作为数组传递

I'm building a multi-page form which I want to commit to the database at the very end of the process, so abandoned forms don't end up littering the data with incomplete junk records, so my initial thought to solve this problem would be to hold the already-submitted data in an array (almost in the same format as it would be had I SELECTed it out of the database), but I seem to be getting pretty confused and ending up with nested arrays and not getting the results I expect when debugging.

So, for example, the first form looks something like this:

<form action="step_2.php" method="post">
    <input type="text" name="textfield1">
    <input type="text" name="textfield2">
    <input type="text" name="options[]">
</form>

(The reason for the array field is since the user can programatically add additional fields, so whilst 'textfield1' & 'textfield2' only has one value, 'options' should be submitted as an array).

What I want to do it just grab the $_POST array and add it to the next field, something like this:

<form action="step_3.php" method="post">
    <input type="hidden" name="form1[]" value="<?=$_POST?>">
    <input type="text" name="textfield3">
    <input type="text" name="options2[]">
</form>

But that doesn't seem to work. Ideally I'd like to end up on the last step of the form either with an array for each form, or a single array organised in a sensible way, e.g.;

[0] => Array
    (
        [textfield1] => Some Text
        [textfield2] => More Text
        [textfield3] => Yet More Text
        [options1] => Array
            (
                [0] => Option A
                [1] => Option B
            )
        [options2] => Array
            (
                [0] => Option E
            )
    )

I'm assuming there's an easier way to do this, but currently my brain is turning to goo trying to wrap a synapse around it.

展开全部

  • 写回答

1条回答 默认 最新

  • dourao3960 2014-01-09 09:23
    关注

    Consider saving the form data in a $_SESSION variable so you aren't passing it back and forth between pageloads.

    For example:

    if( !isset($_SESSION['formdata'])) $_SESSION['formdata'] = array();
    // to add current form data to the array:
    $_SESSION['formdata'] = array_merge($_SESSION['formdata'],$_POST);
    

    This has the added bonus of still working just fine if the user hits the Back button and resubmits an earlier part of the form (it will overwrite the previously saved values)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部