Get unchecked value with PHP

Asked

Viewed 129 times

3

Colleagues.

I have a form that contains the following fields: inserir a descrição da imagem aqui

Note that I selected the first and the third field as order, but when I register in the database, it returns me as follows:

inserir a descrição da imagem aqui

When in fact I had to bring me the null ID 2 and ID 3 as Yes. To try to solve it, I did so:

$valorEncomenda = ($encomendaP[$i] == null)?("Não"):("Sim");

But he’s registered that way:

inserir a descrição da imagem aqui

See below the full code:

Form fields:

<input type="text" name="TamanhoP[]" class="form-control" placeholder="Tamanho">
<input type="text" name="EstoqueProd[]" class="form-control pull-left" placeholder="Estoque">
<input type="checkbox" name="EncomendaProd[]" value="Sim" style="width: 20px">Encomenda

Javascript:

<script type="text/javascript">
$(function () {
  function removeCampo() {
    $(".removerCampo").unbind("click");
    $(".removerCampo").bind("click", function () {
       if($("tr.linhas").length > 1){
        $(this).parent().parent().remove();
       }
    });
  }

  $(".adicionarCampo").click(function () {
    novoCampo = $("tr.linhas:first").clone();
    //novoCampo.find("input").val("");
    novoCampo.find('input[type="text"]').val("");
    novoCampo.find('input[type="checkbox"]').prop('selected', false);
    novoCampo.insertAfter("tr.linhas:last");
    removeCampo();
  });
});
</script>

I take the form values:

$estoqueP = $_POST["EstoqueProd"];
$tamanhoP = $_POST["TamanhoP"]; 
$encomendaP = $_POST["EncomendaProd"];
$metodos->cadastrar($estoqueP,$tamanhoP,$encomendaP);

Registration method():

public function($idProdutos,$estoqueP,$tamanhoP,$encomendaP){

........

 if($estoqueP[0] != ""){
   for($i = 0; $i <= count($tamanho); $i++){
       if($estoqueP[$i] != ""){
          $valorEncomenda = ($encomendaP[$i] == null)?("Não"):("Sim");
           mysqli_query($this->conexao,"INSERT INTO tabela VALUES(null,'".$idProdutos."','".$tamanho[$i]."','".$estoqueP[$i]."','".$valorEncomenda."');");               
       }
   }
 }

........

}

How I can appreciate unchecked?

  • Is using some javascript?

  • Hello rray. Yes. I updated the post.

  • I say use some javascript or ajax when recording? the simplest solution is to exchange the checkbox for a select so always some value is sent. If you use javascript to send the values to php you can still checkbox.

1 answer

2


The way you structured your HTML will not allow you to retrieve the data correctly. Note that, considering three products, you will have something like:

<div>
  <input type="text" name="TamanhoP[]" class="form-control" placeholder="Tamanho">
  <input type="text" name="EstoqueProd[]" class="form-control pull-left" placeholder="Estoque">
  <input type="checkbox" name="EncomendaProd[]" value="Sim" style="width: 20px">Encomenda
</div>

<div>
  <input type="text" name="TamanhoP[]" class="form-control" placeholder="Tamanho">
  <input type="text" name="EstoqueProd[]" class="form-control pull-left" placeholder="Estoque">
  <input type="checkbox" name="EncomendaProd[]" value="Sim" style="width: 20px">Encomenda
</div>

<div>
  <input type="text" name="TamanhoP[]" class="form-control" placeholder="Tamanho">
  <input type="text" name="EstoqueProd[]" class="form-control pull-left" placeholder="Estoque">
  <input type="checkbox" name="EncomendaProd[]" value="Sim" style="width: 20px">Encomenda
</div>

Filling in as in the image provided in the question and making var_dump($_POST) on the server that handles the form submission, we would have something like:

array(3) {
  ["TamanhoP"]=>
  array(3) {
    [0]=>
    string(2) "32"
    [1]=>
    string(2) "33"
    [2]=>
    string(2) "34"
  }
  ["EstoqueProd"]=>
  array(3) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "12"
    [2]=>
    string(2) "13"
  }
  ["EncomendaProd"]=>
  array(2) {
    [0]=>
    string(3) "Sim"
    [1]=>
    string(3) "Sim"
  }
}

Realize that the array EncomendaProd comes with only two values, referring to the first and third product on the form. This was already expected, however, the problem is that we have no way of knowing which products were selected. It could be (1, 2), (1, 3) and (2, 3) that the requisition would be exactly the same. What you should do is differentiate each product from the others. You can do this by indicating the index of each product in the field name, setting the field name itself as a secondary index. For example:

<div>
  <input type="text" name="produtos[0][tamanho]" class="form-control" placeholder="Tamanho">
  <input type="text" name="produtos[0][estoque]" class="form-control pull-left" placeholder="Estoque">
  <input type="checkbox" name="produtos[0][encomenda]" value="Sim" style="width: 20px">Encomenda
</div>
<div>
  <input type="text" name="produtos[1][tamanho]" class="form-control" placeholder="Tamanho">
  <input type="text" name="produtos[1][estoque]" class="form-control pull-left" placeholder="Estoque">
  <input type="checkbox" name="produtos[1][encomenda]" value="Sim" style="width: 20px">Encomenda
</div>
<div>
  <input type="text" name="produtos[2][tamanho]" class="form-control" placeholder="Tamanho">
  <input type="text" name="produtos[2][estoque]" class="form-control pull-left" placeholder="Estoque">
  <input type="checkbox" name="produtos[2][encomenda]" value="Sim" style="width: 20px">Encomenda
</div>

Note that for product 1, each field is defined as a secondary index in produtos[0]. The same for the second product in produtos[1] and for the third product in produtos[2]. This way, when submitting the form, we would have the following result to var_dump($_POST):

array(1) {
  ["produtos"]=>
  array(3) {
    [0]=>
    array(3) {
      ["tamanho"]=>
      string(2) "32"
      ["estoque"]=>
      string(2) "11"
      ["encomenda"]=>
      string(3) "Sim"
    }
    [1]=>
    array(2) {
      ["tamanho"]=>
      string(2) "33"
      ["estoque"]=>
      string(2) "12"
    }
    [2]=>
    array(3) {
      ["tamanho"]=>
      string(2) "34"
      ["estoque"]=>
      string(2) "13"
      ["encomenda"]=>
      string(3) "Sim"
    }
  }
}

Note that for product 2 the index will not be defined encomenda, indicating that it was not selected. To obtain the data, simply iterate on the array $_POST["produtos"]:

foreach ($_POST["produtos"] as $produto) {
    $tamanho = $produto["tamanho"];
    $estoque = $produto["estoque"];
    $encomenda = $produto["encomenda"] ?? "Não";

    echo $tamanho, $estoque, $encomenda, "<br>";
}

Remembering that the null coalescence operator (??) was only inserted in PHP 7. For earlier versions it will be necessary to do: $encomenda = isset($produto["encomenda"]) ? $produto["encomenda"] : "Não".

The way out would be something like:

32 11 Sim
33 12 Não
34 13 Sim
  • Perfect. Thank you Anderson.

Browser other questions tagged

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