json 如何在另一个表单上提交后保留数组中的数据

wi3ka0sx  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(93)

各位,
首先,我很抱歉这个问题有点让人困惑。
问题在于:几天前我发布了另一个问题(this one),关于我们老师给我们的一个练习,这有点棘手,换句话说,这项工作包括将从表单中收集的数据(实际上是几个数据)保存在数组中,然后能够在不删除数组中其他数据的情况下修改它们。
正如我在上一篇文章中所说的,糟糕的是我们不能使用会话、数据库、文件或本地存储。

  • 注意:我在一个页面中完成所有操作,因为这是保存我找到的数据的最佳方式。*

他告诉我们诀窍是使用json_encode()在一个隐藏的输入中传递数据,到目前为止一切都很好,多亏了上一篇文章中的答案,我设法得到了保存多个用户只要NID还没有在数组中,但在我们必须更新数据的部分,一切都变得复杂。要更新数据,我做的第一件事是请求使用select/option修改用户的NID,但是当我提交select时,它删除了我在$agenda变量中添加的用户数据。
我确信问题出在isset()上,但是我已经做了一个星期的练习,我想不出任何新的东西。
下面是index.php的代码:

<?php
require_once './controllers/modules.php';

if(!isset($_POST['hiddenInputUpdate'])) {
    $newAgenda = [];
} else {
    $newAgenda = decodeData();
    updateData($newAgenda);
}

if(!isset($_POST['hiddenInputReg'])) {
    $agenda = [];
} else {
    $agenda = decodeData();
    addData($agenda);
}

print('<pre>'.print_r($agenda, true).'</pre>');

?>
    <div class="container-panel">
        <main>
            <div id="add-contact" class="section-content">
                <div class="top">
                    <div class="left">
                        <h1>Añadir contactos</h1>
                        <div class="date">
                            <input type="date" name="date" id="date">
                        </div>
                    </div>
                    <div class="right">
                        <div class="theme-toggler">
                            <span class="material-icons-sharp active">light_mode</span>
                            <span class="material-icons-sharp">dark_mode</span>
                        </div>
                    </div>
                </div>
                <div>
                    <form action='' method="POST" class="w-75 form-register" id="regForm">
                        <div class="form-floating mb-4">
                            <input type="text" class="form-control form-control-lg" name="regNid" required/>
                            <label for="regNid">DNI</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="text" class="form-control form-control-lg" name="regName" required/>
                            <label for="regName">Nombre</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="text" class="form-control form-control-lg" name="regSurname" required/>
                            <label for="regSurname">Apellidos</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="email" class="form-control form-control-lg" name="regEmail" required/>
                            <label for="regEmail">Email</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="tel" class="form-control form-control-lg" name="regTel" required/>
                            <label for="regTel">Teléfono</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="date" class="form-control form-control-lg" name="regBirth" required/>
                            <label for="regBirth">Fecha de nacimiento</label>
                        </div>

                        <div class="d-flex justify-content-center">
                            <input type="hidden" name="hiddenInputReg" value='<?php echo encodeData($agenda); ?>'>
                            <button type="submit" name="regSubmit" class="btn btn-success btn-block btn-lg gradient-custom-4 text-body">Registrar</button>
                        </div>
                    </form>
                </div>
            </div>
            <div id="update-contact" class="section-content">
                <div class="top">
                    <div class="left">
                        <h1>Actualizar contactos</h1>
                        <div class="date">
                            <input type="date" name="date" id="date">
                        </div>
                    </div>
                    <div class="right">
                        <div class="theme-toggler">
                            <span class="material-icons-sharp active">light_mode</span>
                            <span class="material-icons-sharp">dark_mode</span>
                        </div>
                    </div>
                </div>
                <div>
                    <form class="w-25 my-5" action="" method="POST" id="getNidForm">
                        <select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="getNid">
                            <?php
                            if(isset($agenda)){
                                echo '
                                    <option value="noSel" selected>Selecciona un DNI</option>
                                ';
                                foreach($agenda as $key => $value) {
                                    echo '
                                        <option value='.$key.'>'.$key.'</option>
                                    ';
                                }
                            } else {
                                echo '
                                    <option value="noSel" selected>No hay DNIs</option>
                                ';
                            }
                            ?>
                        </select>
                        <button type="submit" name="getNidSubmit" class="btn btn-success btn-block btn-lg gradient-custom-4 text-body">Seleccionar</button>
                    </form>
                    <?php
                    if(isset($_POST['getNid']) && !empty($_POST['getNid'])) {
                        if($_POST['getNid'] !== 'noSel') {
                            echo '
                            <form class="my-5" action="" method="POST" id="updForm">
                                <div class="form-group">
                                    <h2 class="heading">Registrar</h2>
                                    <div class="form-floating mb-4">
                                        <input type="text" class="form-control form-control-lg" name="updateNid" value="'.$_POST['getNid'].'">
                                        <label for="updateNid">DNI</label>
                                    </div>
                                    <div class="form-floating mb-4">
                                        <input type="text" class="form-control form-control-lg" name="updateName">
                                        <label for="updateName">Nombre</label>
                                    </div>
                                    <div class="form-floating mb-4">
                                        <input type="text" class="form-control form-control-lg" name="updateSurname">
                                        <label for="updateSurname">Apellidos</label>
                                    </div>
                                    <div class="form-floating mb-4">
                                        <input type="email" class="form-control form-control-lg" name="updateEmail">
                                        <label for="updateEmail">Email</label>
                                    </div>       
                                    <div class="form-floating mb-4">
                                        <input type="tel" class="form-control form-control-lg" name="updatePhone">
                                        <label for="updatePhone">Phone</label>
                                    </div>
                                    <div class="form-floating mb-4">
                                        <input type="text" class="form-control form-control-lg" name="updateBirth"/>
                                        <label for="updateBirth">Fecha de nacimiento</label>
                                    </div>
                                    <div class="mb-4" style="width: 22rem;">
                                        <label for="registerPic">Selecciona una foto<span class="text-danger">*</span></label>
                                        <input type="file" class="form-control form-control-lg" name="updateFile" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="grid">
                                    <button type="submit" class="btn btn-primary" name="sub-update" value="update">Actualizar</button>
                                    <input type="hidden" name="hiddenInputUpdate" value='.encodeData($newAgenda).'>
                                    </div>  
                                </div>
                            </form>
                            ';
                        }
                    }
                    ?>
                </div>
            </div>
        </main>
    </div>

这是一个模块。php:

<?php

function getLocalTime() {
    date_default_timezone_set('Atlantic/Canary');
    return date("d-m-Y H:i:s a");
}

function encodeData($data) {
    return json_encode($data);
}

function decodeData() {
    return json_decode($_POST['hiddenInputReg'], true);
}

function cleanData($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

function addData(&$data) {
    $date = getLocalTime();
    if(!in_array($_POST['regNid'], $data) || empty($data)) {
        $data[$_POST['regNid']]['nombre'] = cleanData($_POST['regName']);
        $data[$_POST['regNid']]['apellidos'] = cleanData($_POST['regSurname']);
        $data[$_POST['regNid']]['correo'] = cleanData($_POST['regEmail']);
        $data[$_POST['regNid']]['telefono'] = cleanData($_POST['regTel']);
        $data[$_POST['regNid']]['fechaNacimiento'] = cleanData($_POST['regBirth']);
        $data[$_POST['regNid']]['fechaInsercion'] = $date;
        $data[$_POST['regNid']]['bloqueado'] = false;
        $data[$_POST['regNid']]['ficheros'] = [];
        return;
    }
    return;
}

function updateData(&$data) {
    if(!in_array($_POST['regNid'], $data) || empty($data)) {
        $data[$_POST['regNid']]['nombre'] = cleanData($_POST['regName']);
        $data[$_POST['regNid']]['apellidos'] = cleanData($_POST['regSurname']);
        $data[$_POST['regNid']]['correo'] = cleanData($_POST['regEmail']);
        $data[$_POST['regNid']]['telefono'] = cleanData($_POST['regTel']);
        $data[$_POST['regNid']]['fechaNacimiento'] = cleanData($_POST['regBirth']);
        $data[$_POST['regNid']]['ficheros'] = $_FILES['updateFile']['name'];
        return;
    }
    return;
}

?>
  • 注意:我还没有使用updateDate()函数,但我更愿意将其添加到帖子中以防万一。*

总而言之,我想要实现的是,即使我在#getNidForm或#updForm上提交,也要保留用#regForm添加的数据。

zpgglvta

zpgglvta1#

最后,它非常简单,只需使用相同的隐藏输入#regForm在每个表单中传递数据;您还需要更改条件(isset()),同时考虑到提交按钮(regSubmit、updSubmit或blockSubmit),因为每个按钮都使用不同的函数,例如addData、updateData或setBlock。
如果有人有同样的问题,并有相同的否决权,我把最后的代码在这里:

if(!isset($_POST['hiddenInputReg'])) {
    $agenda = [];
} else {
    $agenda = decodeData();
    if(isset($_POST['regSubmit'])) {
        addData($agenda);
    } 
    else if(isset($_POST['updSubmit'])) {
        updateData($agenda);
    }
    else if(isset($_POST['blockSubmit'])) {
        setBlock($agenda);
    }
}

print('<pre>'.print_r($agenda, true).'</pre>');

?>
    <div class="container-panel">
        <main>
            <div id="add-contact" class="section-content">
                <div class="top">
                    <div class="left">
                        <h1>Añadir contactos</h1>
                        <div class="date">
                            <input type="date" name="date" id="date">
                        </div>
                    </div>
                    <div class="right">
                        <div class="theme-toggler">
                            <span class="material-icons-sharp active">light_mode</span>
                            <span class="material-icons-sharp">dark_mode</span>
                        </div>
                    </div>
                </div>
                <div>
                    <form action='' method="POST" class="w-75 form-register" id="regForm">
                        <div class="form-floating mb-4">
                            <input type="text" class="form-control form-control-lg" name="regNid" required/>
                            <label for="regNid">DNI</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="text" class="form-control form-control-lg" name="regName" required/>
                            <label for="regName">Nombre</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="text" class="form-control form-control-lg" name="regSurname" required/>
                            <label for="regSurname">Apellidos</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="email" class="form-control form-control-lg" name="regEmail" required/>
                            <label for="regEmail">Email</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="tel" class="form-control form-control-lg" name="regTel" required/>
                            <label for="regTel">Teléfono</label>
                        </div>
                        <div class="form-floating mb-4">
                            <input type="date" class="form-control form-control-lg" name="regBirth" required/>
                            <label for="regBirth">Fecha de nacimiento</label>
                        </div>

                        <div class="d-flex justify-content-center">
                            <input type="hidden" name="hiddenInputReg" value='<?php echo htmlspecialchars(encodeData($agenda)); ?>'>
                            <button type="submit" name="regSubmit" class="btn btn-block btn-lg gradient-custom-4 text-body custom-btn">Registrar</button>
                        </div>
                    </form>
                </div>
            </div>
            <div id="update-contact" class="section-content">
                <div class="top">
                    <div class="left">
                        <h1>Actualizar contactos</h1>
                        <div class="date">
                            <input type="date" name="date" id="date">
                        </div>
                    </div>
                    <div class="right">
                        <div class="theme-toggler">
                            <span class="material-icons-sharp active">light_mode</span>
                            <span class="material-icons-sharp">dark_mode</span>
                        </div>
                    </div>
                </div>
                <div>
                    <form class="w-25 my-5" action="" method="POST" id="getNidForm">
                        <select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="getNid">
                            <?php
                            if(isset($agenda)){
                                echo '
                                    <option value="noSel" selected disabled>Selecciona un DNI</option>
                                ';
                                foreach($agenda as $key => $value) {
                                    echo '
                                        <option value='.$key.'>'.$key.'</option>
                                    ';
                                }
                            } else {
                                echo '
                                    <option value="noSel" selected disabled>No hay DNIs</option>
                                ';
                            }
                            ?>
                        </select>
                        <input type="hidden" name="hiddenInputReg" value='<?php echo htmlspecialchars(encodeData($agenda)); ?>'>
                        <button type="submit" name="getNidSubmit" class="btn btn-block btn-lg gradient-custom-4 text-body custom-btn">Seleccionar</button>
                    </form>
                    <?php
                    if(isset($_POST['getNid'])) {
                        foreach($agenda as $key => $val) {
                            if($_POST['getNid'] === $key) {
                                echo '
                                <form class="my-5" action="" method="POST" enctype="multipart/form-data" id="updForm">
                                    <div class="form-group">
                                        <h2 class="heading">Registrar</h2>
                                        <div class="form-floating mb-4">
                                            <input type="text" class="form-control form-control-lg" name="updateNid" value="'.$key.'">
                                            <label for="updateNid">DNI</label>
                                        </div>
                                        <div class="form-floating mb-4">
                                            <input type="text" class="form-control form-control-lg" name="updateName" value="'.$agenda[$key]['nombre'].'">
                                            <label for="updateName">Nombre</label>
                                        </div>
                                        <div class="form-floating mb-4">
                                            <input type="text" class="form-control form-control-lg" name="updateSurname" value="'.$agenda[$key]['apellidos'].'">
                                            <label for="updateSurname">Apellidos</label>
                                        </div>
                                        <div class="form-floating mb-4">
                                            <input type="email" class="form-control form-control-lg" name="updateEmail" value="'.$agenda[$key]['correo'].'">
                                            <label for="updateEmail">Email</label>
                                        </div>       
                                        <div class="form-floating mb-4">
                                            <input type="tel" class="form-control form-control-lg" name="updatePhone" value="'.$agenda[$key]['telefono'].'">
                                            <label for="updatePhone">Phone</label>
                                        </div>
                                        <div class="form-floating mb-4">
                                            <input type="text" class="form-control form-control-lg" name="updateBirth" value="'.$agenda[$key]['fechaNacimiento'].'">
                                            <label for="updateBirth">Fecha de nacimiento</label>
                                        </div>
                                        <div class="mb-4" style="width: 22rem;">
                                            <label for="updateFile">Selecciona una foto<span class="text-danger">*</span></label>
                                            <input type="file" class="form-control form-control-lg" name="updateFile"/>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="grid">
                                            <input type="hidden" name="hiddenInputReg" value="'.htmlspecialchars(encodeData($agenda)).'">
                                            <button type="submit" class="btn custom-btn" name="updSubmit" value="update">Actualizar</button>
                                        </div>  
                                    </div>
                                </form>
                                ';
                            }
                        }
                    }
                    ?>
                </div>
            </div>
        </main>
    </div>

下面是模块.php:

<?php

function getLocalTime($mode) {
    date_default_timezone_set('Atlantic/Canary');
    if($mode === 'datetime') {
        return date("d-m-Y H:i:s a");
    }
    return date("d/m/Y");
}

function encodeData($data) {
    return json_encode($data);
}

function decodeData() {
    return json_decode($_POST['hiddenInputReg'], true);
}

function cleanData($data) {
    $data = trim($data);
    $data = stripslashes($data);
    // $data = htmlspecialchars($data);
    return $data;
}

function addData(&$data) {
    $date = getLocalTime('datetime');
    if(!in_array($_POST['regNid'], $data) || empty($data)) {
        $data[$_POST['regNid']]['nombre'] = cleanData($_POST['regName']);
        $data[$_POST['regNid']]['apellidos'] = cleanData($_POST['regSurname']);
        $data[$_POST['regNid']]['correo'] = cleanData($_POST['regEmail']);
        $data[$_POST['regNid']]['telefono'] = cleanData($_POST['regTel']);
        $data[$_POST['regNid']]['fechaNacimiento'] = cleanData($_POST['regBirth']);
        $data[$_POST['regNid']]['fechaInsercion'] = $date;
        $data[$_POST['regNid']]['bloqueado'] = false;
        $data[$_POST['regNid']]['ficheros'] = [];
    }
    return;
}

function updateData(&$data) {
    $data[$_POST['updateNid']]['nombre'] = cleanData($_POST['updateName']);
    $data[$_POST['updateNid']]['apellidos'] = cleanData($_POST['updateSurname']);
    $data[$_POST['updateNid']]['correo'] = cleanData($_POST['updateEmail']);
    $data[$_POST['updateNid']]['telefono'] = cleanData($_POST['updatePhone']);
    $data[$_POST['updateNid']]['fechaNacimiento'] = cleanData($_POST['updateBirth']);
    $data[$_POST['updateNid']]['ficheros'][] = cleanData($_FILES['updateFile']['name']);
}

function setBlock(&$data) {
    $data[$_POST['block']]['bloqueado'] = !$data[$_POST['block']]['bloqueado'];
}

?>

可能有一些垃圾代码在那里(一些打印或一些不必要的部分),因为我刚刚解决了它,我更喜欢直接上传我所拥有的。
除了将hiddenInputReg放在其他表单或表中(数据在表中更改)之外,关键是调用htmlspecialchars()函数, Package hiddenInputReg的encodeData();从理论上讲,没有在“updSubmit()”表单中添加此函数(在回显中)会导致$agenda数组数据在updateData()函数中看起来为“null”,当然是因为引号的原因,使用htmlspecialchars()它为我解决了这个问题,我还将其放在其他encodeData()中以防万一,但我认为删除除回显之外的所有内容应该没有问题。

相关问题