I am trying to capture the value(s) of a checkbox in php and when printing it it shows me the value "on". could you please help me. This is the code.
<input type="checkbox" name="preferencia[]" value="teatro">Teatro
<input type="checkbox" name="preferencia[]" value="libros">Libros
<input type="checkbox" name="preferencia[]" value="cine">Cine
$preferencias = $_POST["preferencia"];
foreach ($preferencias as $preferencia) {
$pre = $preferencia;
}
//this is the form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Formulario</title>
</head>
<body>
<form method="post" action="datos.php">
<label for="name">Nombre</label>
<input id="name" name="name" type="text"><br>
<br>
<label for="apellido">Apellidos</label>
<input id="apellido" name="apellido" type="text"><br>
<br>
<label >País</label>
<select name="pais[]">
<option value="seleccione" disabled selected>Seleccione</option>
<option value="alemania">Alemania</option>
<option value="italia">Italia</option>
<option value="españa">España</option>
</select><br>
<br>
<label>Preferencias</label><br>
<br>
<input type="checkbox" name="preferencia[]" value="teatro">Teatro
<br>
<input type="checkbox" name="preferencia[]" value="libros">Libros
<br>
<input type="checkbox" name="preferencia[]" value="cine">Cine
<br>
<br>
<button type="submit">Enviar</button>
</form>
</body>
</html>
//este es la de php
<?php
if (count($_POST) > 0) {
$name = $_POST["name"];
$apellido = $_POST["apellido"];
$paises = $_POST["pais"];
$preferencias = $_POST["preferencia"];
foreach ($paises as $pais){
$imp = $pais;
}
foreach ($preferencias as $preferencia) {
$pre = $preferencia;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Respuesta</title>
</head>
<body>
<p>
Nombre: <?=$name?>
</p>
<p>
Apellido: <?=$apellido?>
</p>
<p>
País: <?=$imp?>
</p>
<p>
Preferencia: <?=$pre?>
</p>
</body>
</html>
From what I see, you have not indicated the preference index[]. Here is the functional code. I hope it helps you.
EDIT
This code also works, it is not an index problem as I mentioned before
Surely there is another problem, maybe if you show us the rest of the code, for example how you send or validate the form, we could solve it.
With this last code, the query works. I have limited myself to including the last HTML within the validation of the post so that it does not generate an error on the first page load