Save checkbox in mysql with php

Asked

Viewed 2,104 times

0

I’m trying to save this form in the database but when I got to the checkbox part I couldn’t save it in the bank. Follow 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 in 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);
}

}

  • any errors? gets to mount the query correctly? any clues??

1 answer

1


Hi @Mboss,

Take out 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);

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

$sabendo = $row['sabendo'];
$sabendo_explode = explode(",",$sabendo);
  • 1

    Thank you so much! It worked, solved my problem.

  • Happy to have helped, good job.

Browser other questions tagged

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