Insert in the table only the filled line

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>";

Image:

Codetoinsert:

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 intend to only insert the line in which I fill the checkbox. I show the example in the image and should only insert the line surrounded in red:

    
asked by anonymous 29.11.2018 / 14:54

2 answers

0

I solved this way, but I do not know if it will be the 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 case then it inserts into the database table.

    
29.11.2018 / 15:31
0

I see two possible approaches:

  • Do not send values to the server that are not filled (using Javascript);
  • Filter incoming data on the server and remove unfilled inputs.
  • As data must be validated on the server, option 2 is required but nothing prevents you from using validation on the client along with validation on the server to improve the user experience.

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

    Validation on the client

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

    In the example below I use Element.querySelector() and Element.querySelectorAll() to search for elements in the DOM, iterate over the result and listen for the change event % using Element.addEventListener() .

    Each time the status of a checkbox changes, I loop the DOM starting from% changed, I go up to checkbox using the read-only property tr " if you need compatibility with more "exotic" browsers). Starting with Element.parentElement I'm looking for Element.parentNode , changing its property tr property-based input of disabled "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 whether the element has been selected or not, just receive the cars and they are not empty.

    For this you could use the checked function along with the < to remove all surplus spaces from the elements of the array. After this you can use this "gambiarra" (which in this case is not we really want to filter only strings that are larger than checkbox ) by joining array_map() with trim() to remove the empty strings from our array.

    Once this is done, the result will be only the cars received from the previous 0 fined.

    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.

        
    30.11.2018 / 18:17