2011-03-03 20 views
6

¿Hay una manera fácil de obtener los valores de varias casillas de verificación y almacenarlas en la base de datos?¿Obtiene todos los valores de las casillas de verificación?

<?php 
if(isset($_POST['go'])){ 
    $fruit = $_POST['fruit'].","; 
    echo $fruit; 
    // if you selected apple and grapefruit it would display apple,grapefruit 
} 
?> 
<form method="post"> 
Select your favorite fruit:<br /> 
<input type="checkbox" name="fruit" value="apple" id="apple" /><label for="apple">Apple</label><br /> 
<input type="checkbox" name="fruit" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br /> 
<input type="checkbox" name="fruit" value="grapefruit" id="grapefruit" /><label for="grapefruit">Grapefruit</label><br /> 
<input type="submit" name="go" /> 
</form> 
+1

cambie 'name =" fruit "' a 'name =" fruit [] "', elimine '$ fruit = $ _POST ...', cambie 'echo $ fruit;' a 'echo implode (',', $ _POST ['fruit']) ' – acm

+0

nombre las casillas de verificación" name = fruit [] "para que se envíen a una matriz – Michael

Respuesta

23

Si le da a las casillas de verificación el mismo nombre, que termina en [], los valores se devuelven como una matriz.

<input type="checkbox" name="fruit[]" value="apple" /> 
<input type="checkbox" name="fruit[]" value="grapefruit" /> 

Luego, en PHP ...

if(isset($_POST['fruit']) && is_array($_POST['fruit'])) { 
    foreach($_POST['fruit'] as $fruit) { 
     // eg. "I have a grapefruit!" 
     echo "I have a {$fruit}!"; 
     // -- insert into database call might go here 
    } 

    // eg. "apple, grapefruit" 
    $fruitList = implode(', ', $_POST['fruit']); 
    // -- insert into database call (for fruitList) might go here. 
} 

PS. por favor, perdone el error obvio, que este ejemplo potencialmente gritará "Tengo una manzana" ... No pensé en hacer el ejemplo lo suficientemente inteligente como para determinar cuándo usar "a", y cuándo usar "an": P

5

Nombre de su entrada como esta:

<input type="checkbox" name="fruit[]" value="apple" id="apple" /><label for="apple">Apple</label><br /> 
<input type="checkbox" name="fruit[]" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br /> 

iterar sobre el $ _POST [ 'fruta']:

if(isset($_POST['fruit']) && !empty($_POST['fruit'])) 
    foreach($_POST['fruit'] as $fruit) echo $fruit; 
1

para añadir a las otras soluciones ...

implosionar y explotar puede ser utilizado en PHP para convertir su matriz de fruta [] en una lista separada por comas.

$valueToStoreInDB = implode(",",$_POST['fruit']); 
$fruitAsAnArrayAgain[] = explode(",",$dbvalue); 

vez que tenga su lista separada por comas, un buen tipo de datos para representar las casillas de verificación en MySQL habría SET, y se puede pegar su lista separada separados derecha en su instrucción de inserción.

Cuestiones relacionadas