Product Registration with Select Multiple does not insert all selected

Asked

Viewed 395 times

1

The registered items have various flavors, chocolate, strawberry, vanilla, etc, and each 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>

1 answer

1


Two things need to be fixed. 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 array $_POST['sabor'] to capture all the flavors chosen.

In 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 php, a loop is done (after validation and before the Insert you already do) to capture all flavors. Here’s an important detail: how do you want to save all these flavors? Simply as a single string? Or will save in a ratio 1 for many?

In this example I will put everything as a single string. So it is:

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

When you read this database value a string similar to sabor 1, sabor 2, sabor 3, ....

How complicated it can be to iterate over these values later you might consider using the functions serialize and unserialize. The first converts the structure from an array to a string, and the second can be used to reverse this operation, i.e., to transform it 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" } 
*/

?>
  • Man, everything helped me a lot. But I’m just having trouble with the serialize and unserialize, I don’t know much of php, but what I do know I can manage. If you don’t mind, could you give me an example of this serialize or unserialize for select?

  • 1

    @Thomasfranklin edited the answer to add this example.

  • thanks for the explanation, I will study better the use of how to use the return of the serialize/unserialize when it gets more relaxed over time. I made a really crazy code that worked using explode, array offset and if.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.