Store multiple checkboxes in a single column with PHP + Mysql

Asked

Viewed 2,837 times

2

I’m having trouble storing multiple checkbox in the same table field. In this case, by filling in the form and marking more than one checkbox, it stores only the value of the last checkbox.

Here are some excerpts from the 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 the checkbox onscreen:

<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 genera).

Follow full 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 removed all elseif validation form, 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>';
?>

Now I have an error message: Selected: ,1,2 All checkbox: 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

  • 1

    you need to add clasps [] in the attribute name to transform this into an array, equal in that question

  • I did this, but it persists in recording only the last value.

  • When you give a print_r($_POST['genero']); he comes as?

  • At the beginning of the file where you receive the form data.

  • 1

    Oops! got... Array ( [0] => 1 [1] => 2 ) Thanks ;)

  • 1

    @Henriquesilva, that pile of elseif, else, if..., I suggest you refactor that code better, because it’s really messed up.

  • 1

    You can summarize a lot of this process in fewer lines.

  • @Ivanferrer Actually I can eliminate all validation, because the form will be just for me, and the main problem at the moment is the Insert of multiple values. Can give me a light?

Show 3 more comments

3 answers

3

Gentlemen! Thank you very much to everyone who helped me here. I managed to learn a little more about this language :) .

The following solution is: Includes direct implode function in variable surveys of the $form['genero 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 THANK YOU to all you, and I see that the tips that everyone gave fit the solution, I just was not understand, where to do the integration of implode.

  • That works for my case ? http://answall.com/questions/178382/store%C3%Baltiplos-select-numa-coluna-s%C3%B3-com-php-javascript-mysql

2


The simplest exeplo is to first transform checkboxs into an array, adding []brackets in attribute name, then check if there is any value in $_POST['genero'] if there is make a implode() to turn the array into a comma-delimited string, after all this formatting calls its routine to write to the database, I did a very simple simulation of what it 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')
  • Doubt: as I have several fields in the table, is it possible to summarize calling by array? I put the last code up there. Thanks in advance for your help.

-1

Try to run this code and see that the result is exactly what you want, put the results of various checkbox in a single field in the database, i.e., put the results of several checkbox in 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"; 

    ?>
  • 2

    Put a @ to ignore error is not an appropriate way to solve the problem. This is called gambiarra.

  • @Ivanferrer the real doubt is how to integrate the implode together the validation of the generic field.

  • 1

    The implode has to be in the method $_POST['genero']; and then you store in your generic key array if you need to.

  • Selected: 1,2 All checkbox: 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

  • From what I understand $form has the names of the table fields (see foreach) ... but it seems that they are numbers there generates this syntax error. @Henriquesilva

  • I made a few edits, @Ivanferrer was just using @to test, I forgot to remove and put the correct validation of the variable, but I fixed it. Henriquesilva, please replace the variable $form['genero'] with $form in your code.

  • @Maiconherverton You came to check the last update I did so problem?

  • Yes, the little guy took my code and optimized your problem. I’m glad you solved @Henriquesilva.

Show 3 more comments

Browser other questions tagged

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