Reputation: 14980
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).
$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>
';
}
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?
Upvotes: 0
Views: 783
Reputation: 54841
This happens because $detallesRol
variable 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
Upvotes: 1