Rosamunda Rosamunda - 3 months ago 15
PHP Question

How to update several fields in a single foreach loop?

I have a table with a list of users. Each one has assigned a checkbox. When the admin select some checkboxes my script saves some information into the database for the selected users.

Now, my issue is that beside that checkbox I want to have a text input type so the admin can leave a comment as well for that user. So, when the checkbox is selected and the input type has some data, the data gets saved as well.

This is what I've done so far (besides the obvious issues with security, that I haven't taken into account yet):



My list is generated by a loop for each user:

<input type=text name="infoAdicional" value="'.$x['infoAdicional'].'">
<input name="enviar['.$x['userID'].']" type="checkbox" value="'.$x['userEmail'].'">


I've taken the information and generated a foreach loop for the checkbox, but cannot get the additional information from the text field to get saved (it does update other values:

$userID = $_POST['enviar'];
$infoAdicional = $_POST['infoAdicional'];
foreach ($userID as $id => $email) {
$sql = "UPDATE cursosUsuarios
SET estadoCertificado = 'pending',
infoAdicional='$infoAdicional'
WHERE userID = '$id'
AND email = '$email'
";
...
}


I think that's because
$infoAdicional = $_POST['infoAdicional'];
should be inside the loop, but just inserting it inside it, gets every user with a selected checkbox to have the same additional information, it does repeat itself.

Answer

It doesn't matter if you put the variable $infoAdicional inside the loop or not. The thing is that the last input field with the name overwrites all and therefore you will only have the note of the last user for all. What you need to change is, to make usage of the [] name syntax as you did it with the checkbox.

So your name attribute of the notes field would look like this name="infoAdicional['.$x['userID'].']" and in the loop you would make the assignment of infoAdicional[USERID] to $infoAdicional.

So your code would look like this

$userID = $_POST['enviar']; 
foreach ($userID as $id => $email) {
      $infoAdicional = $_POST['infoAdicional'][$id];
      $sql = "UPDATE cursosUsuarios 
                SET estadoCertificado = 'pending', 
                infoAdicional='$infoAdicional'
                WHERE userID = '$id'
                AND email = '$email'
                ";
      ... 
}

And your HTML code

<input type=text name="infoAdicional['.$x['userID'].']" value="'.$x['infoAdicional'].'">
<input name="enviar['.$x['userID'].']" type="checkbox" value="'.$x['userEmail'].'">
Comments