Rosamunda Rosamunda - 3 months ago 11
PHP Question

How to do a foreach loop in PHP with three dynamic form elements?

I have a form that prepopulate some database information, and I want that same form to save the new information if the user modifies that.

The form have three elements to be saved: roleID, nombreRol and detallesRol

I'm using a foreach loop to get the information, but I just get the roleID and the nombreRol into the foreach, and not the third field. What am I doing wrong?

(Please note that I've not taken into consideration security yet, it's just a proof of concept at the moment).

I show a list of input items



$mostrarRoles = mysqli_query($conectar,$buscarRoles);
while ($roles=mysqli_fetch_array($mostrarRoles)) {
echo '<br><div class="form-group">
Role ID: '.$roles['roleID'].' <b>'.$roles['nombreRol'].'</b>
<input type="text" class="form-control" name="nombreRol['.$roles['roleID'].']" value="'.$roles['nombreRol'].'">
<textarea class="form-control" name="detallesRol[]" rows="2">'.$roles['detallesRol'].'</textarea>
';
}


Now, I put the information inside a foreach loop:



if(isset($_POST['submit'])) {
$rol = $_POST['nombreRol'];
foreach ($rol as $key => $value) {
$roleID = $key;
$nombreRol = $value;
echo 'ID '.$roleID.'<br>';
echo 'Name '.$nombreRol.'<br>';
echo 'Details '.$detallesRol.'<br>';

$guardarRoles = " UPDATE roles
SET nombreRol = '$nombreRol',
detallesRol = '$detallesRol'
WHERE roleID = '$roleID'
";
}
...


When I echo the roleID and the nombreRol variables they do show the user input (and it gets saved to the database), but not the details.

I know that I'm constructing wrong the foreach, how may I correct it?

Answer

This happens because $detallesRolvariable is not defined.

Every value of $roles['detallesRol'] is stored in $_POST['detallesRol'].

So your html output should be changed to

// add roleID as a key
<textarea class="form-control" name="detallesRol[' . $roles['roleID'] . ']" rows="2">'.$roles['detallesRol'].'</textarea>

And in foreach:

foreach ($rol as $key => $value) {
    $roleID = $key;
    $nombreRol = $value;
    $detallesRol = $_POST['detallesRol'][$roleID];
    echo 'Details '.$detallesRol.'<br>';
    // Do update
Comments