$checkboxValues = [];
foreach ($_POST as $key => $value) {
// Verifica si el campo es un checkbox y si está marcado
if (strpos($key, 'baños_opcion') === 0 && isset($_POST[$key])) {
$checkboxValues[] = $_POST[$key];
}
}
}
$toilette = implode(", ", $checkboxValues);
$sql = "INSERT INTO wp_form_submissions (nombre, apellido, email, observaciones, resultado, toilette)
VALUES ('$nombre', '$apellido', '$email', '$observaciones', '$resultado', '$toilette')";
my html
<input type ="hidden" name="baños_opcion6" value="ninguno: 0m"/>
<input type="checkbox" name="baños_opcion6[]" value="0" />
<input type ="hidden" name="baños_opcion7" value="toilette: 2.10m"/>
<input type="checkbox" name="baños_opcion7" value="2.10" />
<input type ="hidden" name="baños_opcion8" value="simple: 4.32m"/>
<input type="checkbox" name="baños_opcion8" value="2.10" />
<input type ="hidden" name="baños_opcion9" value="Antebaño: 8.46m"/>
<input type="checkbox" name="baños_opcion9" value="8.46" />
The array i recieve is :
Datos insertados correctamente en la base de datos.Valores de los campos de checkbox:
ninguno: 0m,
toilette: 2.10m,
simple: 4.32m,
Antebaño: 8.46m
and i only expect the checked option of the user
2
Answers
Ideally, you shouldn’t be mixing in the hidden inputs like this, unless you really need them as they will cause issues like what you have encountered.
The values you are getting in the loop are the hidden input values rather than the checkbox ones.
Since you have the same input name, values will clash.
However, based on the understanding that you need the hidden input’s value corresponding to the checkbox selected, you can try modifying the code as below.
In the HTML separate the name attribute of the hidden inputs and checkboxes.
For the PHP you can change as below
In the PHP portion, the if condition was changed to identify the checkbox name only. As a second step the
$input_key
removes the_check_
to arrive at the name for the hidden input for the checkbox.Full PHP file for the working test
Issue is that you are using the same
name
attribute for both hidden inputs and check boxes. To get only the checked check boxes, you should give uniquename
attributes to each checkbox.HTML:
PHP:
This should work as expected!