Product Registration with Select Multiple does not insert all selected

1

The registered items have several flavors, chocolate, strawberry, vanilla, etc., and each one is inserted by select multiple in the register, it is saved as "chocolate" but the other selected flavors are not inserted.

PHP Code

 if ( ! isset( $_POST ) || empty( $_POST ) ) {
    echo '.';
    echo '<script>';
        echo "Materialize.toast('Impossível continuar!', 4000, 'rounded black');";
        echo '$(".success_v2").removeClass("more");
        $(".success_v2").removeClass("auth");
        $(".loader").hide();
        </script>';
    exit;
}
foreach ( $_POST as $chave => $valor ) {
    $$chave = $valor;
    if ( empty( $valor ) ) {
        echo '.';
        echo '<script>';
        echo "Materialize.toast('Existe campo em branco', 4000, 'rounded red');";
        echo '$(".success_v2").removeClass("more");
        $(".success_v2").removeClass("auth");
        $(".loader").hide();
        </script>';
    }
}
if (   
    ! isset( $nome )
    || ! isset( $marca     )
    || ! isset( $categoria     )
    || ! isset( $peso     )
    || ! isset( $sabor     )
    || ! isset( $prod_destaque     )
    || ! isset( $preco     )
    || ! isset( $codigo     )
    || ! isset( $prod_desconto     )
    || ! isset( $dob     )

) {
    echo '.';
    echo '<script>';
        echo "Materialize.toast('Ainda há campos vázios.', 4000, 'rounded red');";
        echo '$(".success_v2").removeClass("more");
        $(".success_v2").removeClass("auth");
        $(".loader").hide();
        </script>';
    exit;
}
$prepara = $conexao_pdo->prepare("INSERT INTO 'produtos' ('nome','nome_iso','cod','marca','categoria','status','preco','desconto','data','chns','autor','descricao','peso','sabores','cover','prod_destaque','prod_desconto','link') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$verifica = $prepara->execute(
    array(
        $nome,
        $nome_cl,
        $codigo,
        $marca,
        $categoria,
        $dob,
        $preco,
        $desconto,
        $data,
        $chns,
        $autor,
        $descricao,
        $peso,
        $sabor,
        $novo_nome_imagem,
        $prod_destaque,
        $prod_desconto,
        $link_final
    )
);

HTML

<select class="seleciona" name="sabor" multiple="">
    <option disabled selected>Selecione o Sabor</option>
    <option value="chocolate">chocolate</option>
    <option value="morango">morango</option>
    <option value="baunilha">baunilha</option>
</select>
    
asked by anonymous 30.12.2017 / 18:27

1 answer

1

Two things need to be arranged. First change the name attribute of the select tag to name="sabor[]" (This will allow the correct deserialization for the super global $_POST ). And second, iterate over the $_POST['sabor'] array to capture all the flavors you have chosen.

No html gets:

<select class="seleciona" name="sabor[]" multiple="">
    <option disabled selected>Selecione o Sabor</option>
    <option value="chocolate">chocolate</option>
    <option value="morango">morango</option>
    <option value="baunilha">baunilha</option>
</select>

In the php should be done (after validation and before the insert you already do) a for loop to capture all the flavors. Here's an important detail: how will you want to save all those flavors? Simply as a single string? Or will it save on a 1 to many ratio?

In this example I will put everything as a unique string. Then it stays:

$sabor = '';
foreach($_POST['sabor'] as $s){
    $sabor .= ',' . $s;
}
//para remover a primeira virgula
$sabor = ltrim($sabor, ',');

When you read this value from the database, a string similar to sabor 1, sabor 2, sabor 3, ... will be returned.

Since it can be tricky to iterate over these values later on you might consider using serialize and unserialize . The first one converts the structure of a vector to a string, and the second one can be used to revert this operation, that is, to transform back into an array.

Example of serialize and unserialize

<?php
//isso viria de $_POST['sabor']
$sabores = ['sabor1' => 'valor1', 'sabor2' => 'valor2'];
var_dump($sabores);
//imprime um vetor
/*
array(2) { ["sabor1"]=> string(6) "valor1" ["sabor2"]=> string(6) "valor2" }
*/

$serializeSabores = serialize($sabores);
//você poderia salvar a string $serializeSabores no banco
var_dump($serializeSabores);
//imprime uma string (vetor serializado)
/*
string(58) "a:2:{s:6:"sabor1";s:6:"valor1";s:6:"sabor2";s:6:"valor2";}"
*/

//para deserializar. Isso viria do banco como string
$unserializeSabores = unserialize($serializeSabores);
var_dump($unserializeSabores);
//imprime um vetor (string deserializada)
/*
array(2) { ["sabor1"]=> string(6) "valor1" ["sabor2"]=> string(6) "valor2" } 
*/

?>
    
30.12.2017 / 21:37