I only get a checkbox in my database

Asked

Viewed 46 times

-1

I’m making a form with PHP and HTML in which by marking several checkbox I must receive them and enter them into my database.

But I can only get one, for example, if I tick 2 chekbox I’ll just get the last one checkbox selected, what should I do to get all selected?

Man form.php :

<form method="POST" action="cadastra.php">
  <input type="checkbox" name="situacao" value="bom" />bom
  <input type="checkbox" name="situacao" value="regular" />Regular
  <input type="checkbox" name="situacao" value="inrregular" />Inrregular
  <input type="submit" value="Cadastrar" />
</form>

Man cadastrar.php:

$situacao = $_POST['situacao'];
$servidor = "localhost";
$usuario = "root";
$senha = "";
$dbname = "form";

$conn = mysqli_connect($servidor, $usuario, $senha, $dbname); // faz a conexao

//INSERT INTO FORMULARIO SITUACAO = 
//ESCOLHE A TABELA SITUAÇAO  DA TABELA FORMULARIO
//VALUES('$SITUACAO') = RECEBE OS VALORES QUE TÊM  O NAME SITUAÇAO

$result_formulario = "INSERT INTO formulario(situacao) VALUES ('$situacao')"; 
$resultado_formulario = mysqli_query($conn, $result_formulario);

  • Put the code on so it’s easier to help.

  • In the question you say it is a checkbox, but in the code appears a radio.

  • You can not mark more than one radio button. If it was a checkbox you could. If you want to receive all with the same name leave so name="situacao[]" and in php do a foreach to get the values.

  • He tried to edit the question to checkbox, but his edition conflicted with mine, I believe his problem is in PHP.

  • 1

    Checkbox with repeated name needs []

1 answer

2

To register all fields marked, you need to leave the inputs as arrays, and then go through the variable to insert each one.

Follow the modifications made to your code:

HTML

  <input type="checkbox" name="situacao[]" value="bom" />bom
  <input type="checkbox" name="situacao[]" value="regular" />Regular
  <input type="checkbox" name="situacao[]" value="inrregular" />Inrregular

PHP

foreach($situacao as $s) {
    $result_formulario = "INSERT INTO formulario(situacao) VALUES ('$s')";
    $resultado_formulario = mysqli_query($conn, $result_formulario);
}
  • I’d put a if(!empty($_POST['situacao'])){ ... in case no checkbox is a bookmark.

Browser other questions tagged

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