Home > Net >  How to preserve the data in an array after submit on another form
How to preserve the data in an array after submit on another form

Time:11-16

everyone,

First of all, I'm sorry the question is a bit confusing.

The problem is this: I posted another question a few days ago (this one), about an exercise that our teacher has given us and it's a bit tricky, to put it some way, the job consists of saving data collected from a form (several data, in fact), in a array, and then be able to modify them without deleting the other data in the array.

As I said in the previous post, the bad thing is that we can't use sessions, databases, files, or localstorage.

Note: I am doing it all in one page, because it is the best way to preserve the data that I have found.

He told us that the trick was to use json_encode() to pass the data in a hidden input, so far everything is ok, thanks to the answer in the previous post, I managed to get to save more than one user as long as the NID is not already inside the array, but in the part where we have to update the data is where everything gets complicated. To update the data, the first thing I do is ask for the NID of the person to modify with a select/option, but when I submit the select, it deletes the data of the users that I had added in the $agenda variable.

I'm sure the problem is with the isset(), but I've been doing this exercise for a week and I can't think of anything new.

This is the code of 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 >
        <main>
            <div id="add-contact" >
                <div >
                    <div >
                        <h1>Añadir contactos</h1>
                        <div >
                            <input type="date" name="date" id="date">
                        </div>
                    </div>
                    <div >
                        <div >
                            <span >light_mode</span>
                            <span >dark_mode</span>
                        </div>
                    </div>
                </div>
                <div>
                    <form action='' method="POST"  id="regForm">
                        <div >
                            <input type="text"  name="regNid" required/>
                            <label for="regNid">DNI</label>
                        </div>
                        <div >
                            <input type="text"  name="regName" required/>
                            <label for="regName">Nombre</label>
                        </div>
                        <div >
                            <input type="text"  name="regSurname" required/>
                            <label for="regSurname">Apellidos</label>
                        </div>
                        <div >
                            <input type="email"  name="regEmail" required/>
                            <label for="regEmail">Email</label>
                        </div>
                        <div >
                            <input type="tel"  name="regTel" required/>
                            <label for="regTel">Teléfono</label>
                        </div>
                        <div >
                            <input type="date"  name="regBirth" required/>
                            <label for="regBirth">Fecha de nacimiento</label>
                        </div>

                        <div >
                            <input type="hidden" name="hiddenInputReg" value='<?php echo encodeData($agenda); ?>'>
                            <button type="submit" name="regSubmit" >Registrar</button>
                        </div>
                    </form>
                </div>
            </div>
            <div id="update-contact" >
                <div >
                    <div >
                        <h1>Actualizar contactos</h1>
                        <div >
                            <input type="date" name="date" id="date">
                        </div>
                    </div>
                    <div >
                        <div >
                            <span >light_mode</span>
                            <span >dark_mode</span>
                        </div>
                    </div>
                </div>
                <div>
                    <form  action="" method="POST" id="getNidForm">
                        <select  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" >Seleccionar</button>
                    </form>
                    <?php
                    if(isset($_POST['getNid']) && !empty($_POST['getNid'])) {
                        if($_POST['getNid'] !== 'noSel') {
                            echo '
                            <form  action="" method="POST" id="updForm">
                                <div >
                                    <h2 >Registrar</h2>
                                    <div >
                                        <input type="text"  name="updateNid" value="'.$_POST['getNid'].'">
                                        <label for="updateNid">DNI</label>
                                    </div>
                                    <div >
                                        <input type="text"  name="updateName">
                                        <label for="updateName">Nombre</label>
                                    </div>
                                    <div >
                                        <input type="text"  name="updateSurname">
                                        <label for="updateSurname">Apellidos</label>
                                    </div>
                                    <div >
                                        <input type="email"  name="updateEmail">
                                        <label for="updateEmail">Email</label>
                                    </div>       
                                    <div >
                                        <input type="tel"  name="updatePhone">
                                        <label for="updatePhone">Phone</label>
                                    </div>
                                    <div >
                                        <input type="text"  name="updateBirth"/>
                                        <label for="updateBirth">Fecha de nacimiento</label>
                                    </div>
                                    <div  style="width: 22rem;">
                                        <label for="registerPic">Selecciona una foto<span >*</span></label>
                                        <input type="file"  name="updateFile" />
                                    </div>
                                </div>
                                <div >
                                    <div >
                                    <button type="submit"  name="sub-update" value="update">Actualizar</button>
                                    <input type="hidden" name="hiddenInputUpdate" value='.encodeData($newAgenda).'>
                                    </div>  
                                </div>
                            </form>
                            ';
                        }
                    }
                    ?>
                </div>
            </div>
        </main>
    </div>

And this is the modules.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;
}

?>

Note: I haven't used the updateDate() function yet, but I preferred to add it to the post just in case.

To summarize, what I want to achieve is to keep the data added with the #regForm even if I submit on the #getNidForm or the #updForm .

CodePudding user response:

In the end it was as simple as passing the data in each form with the same hidden input of #regForm; you also need to change the conditions (the isset()) taking into account the submit button (regSubmit, updSubmit or blockSubmit) since each of them use different functions, such as addData, updateData or setBlock.

In case someone has the same problem and has the same vetoes as me, I leave the final code here:

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 >
        <main>
            <div id="add-contact" >
                <div >
                    <div >
                        <h1>Añadir contactos</h1>
                        <div >
                            <input type="date" name="date" id="date">
                        </div>
                    </div>
                    <div >
                        <div >
                            <span >light_mode</span>
                            <span >dark_mode</span>
                        </div>
                    </div>
                </div>
                <div>
                    <form action='' method="POST"  id="regForm">
                        <div >
                            <input type="text"  name="regNid" required/>
                            <label for="regNid">DNI</label>
                        </div>
                        <div >
                            <input type="text"  name="regName" required/>
                            <label for="regName">Nombre</label>
                        </div>
                        <div >
                            <input type="text"  name="regSurname" required/>
                            <label for="regSurname">Apellidos</label>
                        </div>
                        <div >
                            <input type="email"  name="regEmail" required/>
                            <label for="regEmail">Email</label>
                        </div>
                        <div >
                            <input type="tel"  name="regTel" required/>
                            <label for="regTel">Teléfono</label>
                        </div>
                        <div >
                            <input type="date"  name="regBirth" required/>
                            <label for="regBirth">Fecha de nacimiento</label>
                        </div>

                        <div >
                            <input type="hidden" name="hiddenInputReg" value='<?php echo htmlspecialchars(encodeData($agenda)); ?>'>
                            <button type="submit" name="regSubmit" >Registrar</button>
                        </div>
                    </form>
                </div>
            </div>
            <div id="update-contact" >
                <div >
                    <div >
                        <h1>Actualizar contactos</h1>
                        <div >
                            <input type="date" name="date" id="date">
                        </div>
                    </div>
                    <div >
                        <div >
                            <span >light_mode</span>
                            <span >dark_mode</span>
                        </div>
                    </div>
                </div>
                <div>
                    <form  action="" method="POST" id="getNidForm">
                        <select  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" >Seleccionar</button>
                    </form>
                    <?php
                    if(isset($_POST['getNid'])) {
                        foreach($agenda as $key => $val) {
                            if($_POST['getNid'] === $key) {
                                echo '
                                <form  action="" method="POST" enctype="multipart/form-data" id="updForm">
                                    <div >
                                        <h2 >Registrar</h2>
                                        <div >
                                            <input type="text"  name="updateNid" value="'.$key.'">
                                            <label for="updateNid">DNI</label>
                                        </div>
                                        <div >
                                            <input type="text"  name="updateName" value="'.$agenda[$key]['nombre'].'">
                                            <label for="updateName">Nombre</label>
                                        </div>
                                        <div >
                                            <input type="text"  name="updateSurname" value="'.$agenda[$key]['apellidos'].'">
                                            <label for="updateSurname">Apellidos</label>
                                        </div>
                                        <div >
                                            <input type="email"  name="updateEmail" value="'.$agenda[$key]['correo'].'">
                                            <label for="updateEmail">Email</label>
                                        </div>       
                                        <div >
                                            <input type="tel"  name="updatePhone" value="'.$agenda[$key]['telefono'].'">
                                            <label for="updatePhone">Phone</label>
                                        </div>
                                        <div >
                                            <input type="text"  name="updateBirth" value="'.$agenda[$key]['fechaNacimiento'].'">
                                            <label for="updateBirth">Fecha de nacimiento</label>
                                        </div>
                                        <div  style="width: 22rem;">
                                            <label for="updateFile">Selecciona una foto<span >*</span></label>
                                            <input type="file"  name="updateFile"/>
                                        </div>
                                    </div>
                                    <div >
                                        <div >
                                            <input type="hidden" name="hiddenInputReg" value="'.htmlspecialchars(encodeData($agenda)).'">
                                            <button type="submit"  name="updSubmit" value="update">Actualizar</button>
                                        </div>  
                                    </div>
                                </form>
                                ';
                            }
                        }
                    }
                    ?>
                </div>
            </div>
        </main>
    </div>

Here is the modules.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'];
}

?>

There may be some trash code out there (some print or some unnecessary part), since I just solved it, I preferred to directly upload what I had.

The key, in addition to putting the hiddenInputReg in the other forms or in the table, which is where the data is changed, was to call the htmlspecialchars() function, wrapping the encodeData() of the hiddenInputReg; in theory, not adding this function in the "updSubmit()" form (which is in an echo) caused the $agenda array data look as "null" at the updateData() function, surely because of the quotes, with the htmlspecialchars() it solved it for me, I also put it in the other encodeData() just in case, but I think that deleting all except in the echos, it should work without problem.

  • Related