2011-07-30 6 views
11

tengo varias casillas de verificación en mi formulario:¿Cómo manejar múltiples casillas de verificación en un formulario de PHP?

<input type="checkbox" name="animal" value="Cat" /> 
<input type="checkbox" name="animal" value="Dog" /> 
<input type="checkbox" name="animal" value="Bear" /> 

Si puedo comprobar los tres y pulse enviar, con el siguiente código en el script PHP:

if(isset($_POST['submit']) { 
    echo $_POST['animal']; 
} 

consigo "mono", es decir, el último valor de casilla seleccionado aunque elegí los tres. ¿Cómo obtener los 3?

Respuesta

20

ver los cambios que he hecho en el nombre:

<input type="checkbox" name="animal[]" value="Cat" /> 
<input type="checkbox" name="animal[]" value="Dog" /> 
<input type="checkbox" name="animal[]" value="Bear" /> 

usted tiene que configurarlo como matriz.

print_r($_POST['animal']); 
3

uso de corchetes al lado del nombre del campo

<input type="checkbox" name="animal[]" value="Cat" /> 
<input type="checkbox" name="animal[]" value="Dog" /> 
<input type="checkbox" name="animal[]" value="Bear" /> 

En el lado de PHP, se puede tratar como cualquier otra matriz.

16
<input type="checkbox" name="animal[]" value="Cat" /> 
<input type="checkbox" name="animal[]" value="Dog" /> 
<input type="checkbox" name="animal[]" value="Bear" /> 

Si puedo comprobar los tres y pulse enviar, con el siguiente código en el script PHP:

if(isset($_POST['animal'])){ 
    foreach($_POST['animal'] as $animal){ 
     echo $animal; 
    } 
} 
Cuestiones relacionadas