Store multiple checkboxes in a column with only PHP + MySQL

2

I am having difficulty storing multiple checkbox in the same field as the table. In this case, when filling out the form and marking more than one checkbox , it stores only the value of the last checkbox .

Here are some snippets of code related to checkbox :

Code PHP :

$form['genero'] =  $_POST['genero'];
elseif (isset($form['genero']))
$r1 = implode(",", $form['genero']);  //<<<< Não funcionou

Code PHP to write checkbox on screen:

<div class="form-group col-md-4">
              <label for="campo11">Selecione o Gênero</label><br>
                <?php 
                    foreach ($generos as $categ) {
                    echo '<input type="checkbox" name="genero[]" value="'. $categ['id'].'">'. $categ['genero'] .'</input><br>'; 
                } ?>
            <br>
            </div>

The checkbox are generated by a table that contains the ID and Name (table genres).

Follow the complete PHP code.

    <?php 

    $generos    =   DBRead('generos', 'ORDER BY genero DESC');

    if( !$generos)
        echo '<h2>Você não possui generos cadastradas, <a href="add-categ.php">clique aqui para resolver isto</a>!</h2>';
    else {

        if(isset($_POST['publicar'])){
            $form['tipo']       = DBEscape( strip_tags( trim( $_POST['tipo']) ) );
            $form['titulo']     = DBEscape( strip_tags( trim( $_POST['titulo']) ) );
            //$form['genero']       = DBEscape( strip_tags( trim( $_POST['genero']) ) );                
            $form['qualidade']  = DBEscape( strip_tags( trim( $_POST['qualidade']) ) );
            $form['imdb']       = DBEscape( strip_tags( trim( $_POST['imdb']) ) );
            $form['lancamento']     = DBEscape( strip_tags( trim( $_POST['lancamento']) ) );
            $form['direcao']    = DBEscape( strip_tags( trim( $_POST['direcao']) ) );
            $form['elenco'] = DBEscape( strip_tags( trim( $_POST['elenco']) ) );
            $form['conteudo']   = str_replace( '\r\n', "\n", DBEscape( trim( $_POST['conteudo']) ) );

            $form['url1']       = DBEscape( strip_tags( trim( $_POST['url1']) ) );              
            $form['genero'] = $_POST['genero'];
            $form['status']     = DBEscape( strip_tags( trim( $_POST['status']) ) );
            $form['data']       = date('Y-m-d H:i:s');


            if (empty( $form ['tipo'] ))
                echo '<div class="alert alert-info" role="alert">Preencha o tipo.</div>';
            elseif  (empty( $form ['titulo'] ))
                echo '<div class="alert alert-info" role="alert">Preencha o titulo.</div>';
            //elseif (empty( $form ['genero']))
            //  echo '<div class="alert alert-info" role="alert">Preencha o gênero.</div>';
            elseif (empty( $form ['qualidade']))
                echo '<div class="alert alert-info" role="alert">Preencha o Qualidade.</div>';
            elseif (empty( $form ['imdb']))
                echo '<div class="alert alert-info" role="alert">Preencha o IMDB.</div>';
            elseif (empty( $form ['lancamento']))
                echo '<div class="alert alert-info" role="alert">Preencha o Lançamento.</div>';
             elseif (empty( $form ['direcao']))
                echo '<div class="alert alert-info" role="alert">Preencha a Direção.</div>';
             elseif (empty( $form ['elenco']))
                echo '<div class="alert alert-info" role="alert">Preencha o Elenco.</div>';
             elseif (empty( $form ['conteudo'])) 
                echo '<div class="alert alert-info" role="alert">Preencha o conteudo.</div>';

            //elseif (empty( $form ['capa'])) 
                //echo '<div class="alert alert-info" role="alert">Preencha o capa do filme.</div>';

            elseif (empty( $form ['url1'])) 
                echo '<div class="alert alert-info" role="alert">Preencha o URL 1.</div>';

             elseif (empty($form['genero']))
                echo '<div class="alert alert-info" role="alert">Preencha o campo categoria.</div>';

             elseif (empty( $form ['status']) && $form['status'] != '0') 
                echo '<div class="alert alert-info" role="alert">Preencha o status.</div>';
             else {
                $dbCheck = DBRead('posts', "WHERE titulo ='". $form['titulo'] . "'"); /*Checa se já existe algum titulo igual no banco*/
                if($dbCheck)
                    echo '<div class="alert alert-warning" role="alert">Já existe uma postagem com este titulo.</div>';
                else {
                    if( DBCreate('posts', $form ) )
                        echo '<div class="alert alert-success" role="alert">Sua postagem foi enviada com sucesso.</div>';
                    else {
                        echo '<div class="alert alert-danger" role="alert">Desculpe ocorreu um erro</div>';
                    }
                }
             }



            echo '<hr>';
        }

?>

I've removed all form validation elseif, to work only with checkboxes ...

    <?php 

    $generos    =   DBRead('generos', 'ORDER BY genero DESC');

    if( !$generos)
        echo '<h2>Você não possui generos cadastradas, <a href="add-categ.php">clique aqui para resolver isto</a>!</h2>';
    else {

        if(isset($_POST['publicar'])){
            $form['tipo']       = DBEscape( strip_tags( trim( $_POST['tipo']) ) );
            $form['titulo']     = DBEscape( strip_tags( trim( $_POST['titulo']) ) );
            //$form['genero']       = DBEscape( strip_tags( trim( $_POST['genero']) ) );                
            $form['qualidade']  = DBEscape( strip_tags( trim( $_POST['qualidade']) ) );
            $form['imdb']       = DBEscape( strip_tags( trim( $_POST['imdb']) ) );
            $form['lancamento']     = DBEscape( strip_tags( trim( $_POST['lancamento']) ) );
            $form['direcao']    = DBEscape( strip_tags( trim( $_POST['direcao']) ) );
            $form['elenco'] = DBEscape( strip_tags( trim( $_POST['elenco']) ) );
            $form['conteudo']   = str_replace( '\r\n', "\n", DBEscape( trim( $_POST['conteudo']) ) );
            $form['url1']       = DBEscape( strip_tags( trim( $_POST['url1']) ) );              
            $form['status']     = DBEscape( strip_tags( trim( $_POST['status']) ) );
            $form['data']       = date('Y-m-d H:i:s');
                $r1 = "";
                $valor = "";
                $camposSelecionados= "";
                $form = array();
                if (isset($_POST['genero'])){
                $form =  $_POST['genero'];

                    foreach($form as $valor){
                        if (!empty($valor)){
                            $camposSelecionados .= ",$valor";
                        }
                    }

                 $r1 = implode(",", $form);
                }

                echo "Selecionados: $camposSelecionados<br>";
                echo "Todos os checkbox: $r1"; 


                    if( DBCreate('posts', $form ) )
                        echo '<div class="alert alert-success" role="alert">Sua postagem foi enviada com sucesso.</div>';
                    else {
                        echo '<div class="alert alert-danger" role="alert">Desculpe ocorreu um erro</div>';
                    }
                }

            echo '<hr>';
?>

I now have an error message: Selected:, 1,2 All checkboxes: 1,2You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0, 1) VALUES (' 1 ',' 2 ')' at line 1

    
asked by anonymous 24.08.2015 / 14:07

3 answers

2
The simplest example is to first transform the checkboxes into an array by adding% with brackets% in the [] attribute, then check if there is any value in name if there is a $_POST['genero'] to turn the array into a string delimited by commas, after all this formatting calls its routine to record in the bank, I made a simulation very simple of what would be.

<form action="" method="POST">
    1<input name="genero[]" type="checkbox" value="1" /><br>
    2<input name="genero[]" type="checkbox" value="2" /><br>
    3<input name="genero[]" type="checkbox" value="3" /><br>
    4<input name="genero[]" type="checkbox" value="4" /><br>
    5<input name="genero[]" type="checkbox" value="5" /><br>
    6<input name="genero[]" type="checkbox" value="6" /><br>
    7<input name="genero[]" type="checkbox" value="7" /><br>
    8<input name="genero[]" type="checkbox" value="8" />
    <input name="" type="submit" value="Submit" />
</form>
<?php

if(!empty($_POST['genero']) && count($_POST['genero']) ){
    $itens = implode(',', $_POST['genero']);

    //sql simulada
    $sql = "INSERT INTO tabela (id, nome, descricao, itens) VALUES (1, 'nome valor', 'descricao valor', '$itens')";
    echo $sql;
}

?>

Output is something like

INSERT INTO tabela (id, nome, descricao, itens) VALUES (1, 'nome valor', 'descricao valor', '1,2,5')
    
24.08.2015 / 16:12
3

Gentlemen! Many thanks to all who helped me here. I was able to learn more about this language :).

Follow this solution: It includes the direct implode function in the multiples of the $ form ['gender'] array.

            $form['genero'] = implode(',', $_POST['genero']);           

            elseif (empty($_POST['genero']) && count($_POST['genero']) <= 5 )
                echo '<div class="alert alert-info" role="alert">Preencha o gênero.</div>';

I leave a MUCH thank you to all of you, and I see that the tips we all gave fit the solution, I just was not understanding, where to do the implode integration.

    
24.08.2015 / 19:26
-1

Try to execute this code and see that the result is exactly what you want, put the results of several checkbox into a single field in the database, that is, put the results of several checkbox into a single string .

   <form action="" method="POST">
<input name="genero[]" type="checkbox" value="1" checked="checked" />
<input name="genero[]" type="checkbox" value="2"  />
<input name="genero[]" type="checkbox" value="3" checked="checked" />
<input name="genero[]" type="checkbox" value="4"  />
<input name="genero[]" type="checkbox" value="5" checked="checked" />
<input name="genero[]" type="checkbox" value="6"  />
<input name="genero[]" type="checkbox" value="7" checked="checked" />
<input name="genero[]" type="checkbox" value="8" />
<input name="" type="submit" value="Submit" />
</form>

PHP code:

<?php 


$r1 = "";
$valor = "";
$camposSelecionados= "";
$form = array();
if (isset($_POST['genero'])){
$form =  $_POST['genero'];

    foreach($form as $valor){
        if (!empty($valor)){
            $camposSelecionados .= ",$valor";
        }
    }
 if (strlen($camposSelecionados)>0){
    $camposSelecionados = substr($camposSelecionados,1,strlen($camposSelecionados));    
 }
 $r1 = implode(",", $form);
}

echo "Selecionados: $camposSelecionados<br>";
echo "Todos os checkbox: $r1"; 

    ?>
    
24.08.2015 / 14:40