Save checkbox in mysql with php

0

I'm trying to save this form to the database but when I got to the checkbox I could not save it to the database. Here are the codes I tried to use.

HTML:

<div class="col-sm-12">
<label><b>Como você ficou sabendo do empreendimento? <span>*</span> </b></label>
<div class="form-check">
    <input class="form-check-input" type="checkbox" value="Site" name="sabendo[]">
    <label class="form-check-label" for="defaultCheck1">Site</label>
</div>
<div class="form-check">
    <input class="form-check-input" type="checkbox" value="Facebook" name="sabendo[]">
    <label class="form-check-label" for="defaultCheck1">Fecebook</label>
</div>
<div class="form-check">
    <input class="form-check-input" type="checkbox" value="Google" name="sabendo[]">
    <label class="form-check-label" for="defaultCheck1">Google</label>
</div>
<div class="form-check">
    <input class="form-check-input" type="checkbox" value="Jornal" name="sabendo[]">
    <label class="form-check-label" for="defaultCheck1">Jornal</label>
</div>
<div class="form-check">
    <input class="form-check-input" type="checkbox" value="Panfletos" name="sabendo[]">
    <label class="form-check-label" for="defaultCheck1">Panfleto</label>
</div>
<div class="form-check">
    <input class="form-check-input" type="checkbox" value="Imobiliaria" name="sabendo[]">
    <label class="form-check-label" for="defaultCheck1">Imobiliária</label>
</div>
<div class="form-check">
    <input class="form-check-input" type="checkbox" value="Outros" name="sabendo[]">
    <label class="form-check-label" for="defaultCheck1">Outros</label>
</div>

PHP Saving to the bank:

if(isset($_POST['sabendo'])){
$listaCheckbox = $_POST['sabendo'];
foreach ($listaCheckbox as $sabendo) {
    echo $sabendo;
    $sql = "INSERT INTO form_cidades (nome, email, tempo, cordialidade, info, comentario, sabendo, imobi) VALUES('$nome', '$email', '$tempo', '$cordialidade', '$info', '$comentario', '$sabendo', '$imobi')";
    $resultado = mysqli_query($conexao, $sql);
}

}

    
asked by anonymous 10.07.2018 / 14:24

1 answer

1

Hi @MBoss,

Take the foreach, and use an implode, it would look like this:

$sabendo = $_POST['sabendo'];
$sabendo_implode = implode(",",$sabendo);

$sql = "INSERT INTO form_cidades (nome, email, tempo, cordialidade, info, comentario, sabendo, imobi) VALUES('$nome', '$email', '$tempo', '$cordialidade', '$info', '$comentario', '$sabendo_implode ', '$imobi')";
    $resultado = mysqli_query($conexao, $sql);

In this way, you will save all the values of the marked checkboxes, separated by commas within the "knowing" field. When you want to read them via select it does the explode like this:

$sabendo = $row['sabendo'];
$sabendo_explode = explode(",",$sabendo);
    
10.07.2018 / 14:39