Insert only the populated row in the table

Asked

Viewed 55 times

0

Table code:

$j = 0;
while($rows_cursos1 = mysqli_fetch_array($resultado_cursos1)) {

$tabela2 .= '<tr>';

$tabela2 .= '<td> <input type="text" readonly="true" size="20" name= "Carro[]" id= "Carro" value="'.$rows_cursos1['Descricao'].'"></td>';

$tabela2 .= '<td style="float:center"> <input type="checkbox" name= "Selecionado['.$j.']" value="X">';

$tabela2 .= '</tr>'; 
$j++;
}
echo "<form method='POST' action=''>";
echo $tabela2;
echo "<input type='submit' name='registar' value='Registo'>";

echo "</form>";

Imagery:

inserir a descrição da imagem aqui

Code to insert:

if(isset($_POST['registar']))
{

$Carro = $_POST['Carro'];


for ($i=0;$i<count($_POST["Carro"]);$i++) { 
$car = $_POST['Carro'][$i];
$selecionado = $_POST['Selecionado'][$i];  

 $stmt = $conn->prepare("INSERT INTO Registolistagem (Carro, Selecionado) VALUES ('$car', '$selecionado')");
    mysqli_stmt_execute($stmt); 

}
}

You are entering the 6 types of cars that exist in the table, but I just want you to enter the line where I fill the checkbox. I show example in the image and should only insert the line surrounded in red:

inserir a descrição da imagem aqui

2 answers

0


I decided this way, but I don’t know if it’s best practice:

if(isset($_POST['registar']))
{

$Carro = $_POST['Carro'];


for ($i=0;$i<count($_POST["Carro"]);$i++) { 
$car = $_POST['Carro'][$i];
$selecionado = $_POST['Selecionado'][$i];  

if( $selecionado != ""){

$selecionado = $selecionado == "on" ? "X" : "";
 $stmt = $conn->prepare("INSERT INTO Registolistagem (Carro, Selecionado) VALUES ('$car', '$selecionado')");
    mysqli_stmt_execute($stmt); 

}
}
}

I added an if to check if the chckbox is different from empty and if that’s the only case you insert in the database table.

0

I see two possible approaches:

  1. Do not send values that are not filled in to the server (using Javascript);
  2. Filter incoming data on the server and remove unfilled inputs.

Since data should be validated on the server, option 2 is mandatory but nothing prevents you from using client validation along with server validation to improve user experience.

I’ll try to explain how it can be done:

Validation in the client

You can use javascript to modify the property disabled inputs, this way the browser will send only inputs that are disabled = false.

In the following example use Element.querySelector() and Element.querySelectorAll() to search for the elements in the GIFT, I spend time on the result and listen to the event change using Element.addEventListener().

Each time the state of a checkbox changes, I go through the DOM starting from the checkbox altered, I go up to the tr using the read-only property Element.parentElement (you can use Element.parentNode if you need compatibility with more "exotic" browsers). Starting from tr I seek the input, changing your property disabled property-based checked of checkbox "clicked".

let checks = document.querySelectorAll('.check')

for (let i=0, l=checks.length ; i<l ; i++) {
    checks[i].addEventListener('change', function(event) {
        let tr = this.parentElement.parentElement.parentElement
        tr.querySelector('.carro').disabled = !this.checked
    })
}
<table>
  <thead>
    <tr>
      <th>Carro</th>
      <th>Selecione</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input name="Carro[]" class="carro" value="Modelo 1"></td>
      <td>
        <label>
          <input class="check" type="checkbox" checked>
        </label>
      </td>
    </tr>
    <tr>
      <td><input name="Carro[]" class="carro" value="Modelo 2"></td>
      <td>
        <label>
          <input class="check" type="checkbox" checked>
        </label>
      </td>
    </tr>
    <tr>
      <td><input name="Carro[]" class="carro" value="Modelo 3"></td>
      <td>
        <label>
          <input class="check" type="checkbox" checked>
        </label>
      </td>
    </tr>
  </tbody>
</table>

Server Validation

Apparently there is no need for you to receive on the server if the element was selected or not, just receive the cars and these are not empty.

For this you could use the function array_map() along with the function trim() to remove all excess spaces from the array elements. After that you can use this "gambiarra" (which in this case is not because we really want to filter only strings that have larger size than 0) joining together array_filter with strlen to remove empty strings from our array.

Once this is done the result will only be the cars received from form previous that are filled.

Example:

<?php

$carros = ["Modelo 1", "", "      ", "Modelo 2"];

// Remover espaços
$carros = array_map('trim', $carros);

// Remover elementos vazios
$carros = array_filter($carros, 'strlen');

Repl.it with the code working.

Browser other questions tagged

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