Insert from a table with for

Asked

Viewed 54 times

0

I have the following html:

<?php
$j=0;
    while($rows_cursos1 = mysqli_fetch_array($resultado_cursos1)) {
?>

<tr>
<td style="display: none"><input type="text" name="NomeUtente[]" class="NomeUtente" value="<?php echo $rows_cursos1 ["codigo"]; ?>"></td>
<td style="font-size: 12px"><?php echo $rows_cursos1['nome']; ?></td>
<td style="display: none"><input type="text" name="Quarto[]" class="Quarto" value="<?php echo $rows_cursos1 ["quarto"]; ?>"></td>
<td style="font-size: 12px"><?php echo $rows_cursos1['quarto']; ?></td>
<td style="display: none"><input type="text" name="Cama[]" class="Cama" value="<?php echo $rows_cursos1 ["Cama"]; ?>"></td>
<td style="font-size: 12px"><?php echo $rows_cursos1['Cama']; ?></td>
<ul class="flex-outer">
<td style="font-size: 12px"><div class="form-check">
<label class="toggle">
<input type="checkbox" class="form-control" name="Miccao[<?php $j; ?>]"><span class="label-text"> Realizado</span> <input class="form-control" type="text" name= "Tipo1[]" class= "Tipo1">
</label>
</div></td>
<td style="font-size: 12px"><div class="form-check">
<label class="toggle">
<input type="checkbox" class="form-control" name="Dejeccao[<?php $j; ?>]"><span class="label-text"> Realizado</span> <input class="form-control" type="text" name= "Tipo[]" class= "Tipo">
</label>
</div></td>
</ul>
</tr>
<?php
$j++;
    }
?>

Then send the data to the php page with the following function:

function inserir_registo26()
{   
   var NomeUtente = [];
    $("input[name^='NomeUtente']").each(function() {NomeUtente.push(this.value)});

    var Quarto = [];
    $("input[name^='Quarto']").each(function() {Quarto.push(this.value)});

    var Cama = [];
    $("input[name^='Cama']").each(function() {Cama.push(this.value)});

    var Miccao = [];
    $("input[name^='Miccao']:checked").each(function() {Miccao.push(this.value)});

    var Tipo1 = [];
    $("input[name^='Tipo1']").each(function() {Tipo1.push(this.value)});

    var Dejeccao = [];
    $("input[name^='Dejeccao']:checked").each(function() {Dejeccao.push(this.value)});

    var Tipo = [];
    $("input[name^='Tipo']").each(function() {Tipo.push(this.value)});

    var dadosajax = {
     'NomeUtente[]' : NomeUtente,
     'Quarto[]' : Quarto,
     'Cama[]' : Cama,
     'Miccao[]' : Miccao,
     'Tipo1[]' : Tipo1,
     'Dejeccao[]' : Dejeccao,
     'Tipo[]' : Tipo
    };
console.log(dadosajax);
    $.ajax({
        url: './registomiccao',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){
          $(".error_message").removeClass('hide');
        },
        success: function(result)
        { 
        $('.form11')[0].reset();
        Swal.fire('Boa!', 'Gravado com sucesso!', 'success');
        }
    });

php have it like this:

for ($i=0;$i<count($_POST["NomeUtente"]);$i++) { 

$NomeUtente = $_POST["NomeUtente"][$i];
$Quarto = $_POST["Quarto"][$i];
$Cama = $_POST['Cama'][$i];
$miccao = $_POST["Miccao"][$i];
$Tipo1 = $_POST["Tipo1"][$i];
$dejeccao = $_POST["Dejeccao"][$i];
$Tipo = $_POST["Tipo"][$i];
$Colaborador = $_SESSION['usuarioId'];
$DataRegisto = date("Y-m-d H:i:s");

if( $miccao != ""){

$miccao1 = $miccao == "on" ? "Realizado" : ""; 

    $query = 'INSERT INTO registoMiccao (`NomeUtente`, `Quarto`, `Cama`, `DataRegisto`, `Miccao`, `Tipo1`, `Colaborador`) VALUES ( ?, ?, ?, ?, ?, ?, ?)';
            $stmt = $conn->prepare( $query );
            $stmt->bind_param("sssssss", $NomeUtente, $Quarto, $Cama, $DataRegisto, $miccao1, $Tipo1, $Colaborador);
            $stmt->execute();
}
if( $dejeccao != ""){

$dejeccao1 = $dejeccao == "on" ? "Realizado" : "";  

    $query1 = 'INSERT INTO registoDejeccao (`NomeUtente`, `Quarto`, `Cama`, `DataRegisto`, `Dejeccao`, `Tipo`, `Colaborador`) VALUES ( ?, ?, ?, ?, ?, ?, ?)';
            $stmt1 = $conn->prepare( $query1 );
            $stmt1->bind_param("sssssss", $NomeUtente, $Quarto, $Cama, $DataRegisto, $dejeccao1, $Tipo, $Colaborador);
            $stmt1->execute();
}       
}

When I’m about to enter, I should just enter the data from the lines I check the checkboxes on. But what’s happening is that if I check the checkbox on two lines, it inserts only two lines, but the data doesn’t belong to the lines where I checked the checkboxes.

For example if I check line 19 and 20 it inserts the data of line 1 and 2 and should enter the data of lines 19 and 20, because they were the ones I checked.

The problem is on these lines:

$("input[name^='Miccao']:checked").each(function() {Miccao.push(this.value)});
$("input[name^='Dejeccao']:checked")

Because when I send the arrays, in all variables it sends 46 lines and in the checkbox it only sends the number of arrays I select, as shown here.

{User[]: Array(46), Room[]: Array(46), Bed[]: Array(46), Miccao[]: Array(2), Type1[]: Array(46), ...}

but if you don’t put the :checked in the two lines above it will bring everything as on, as if they were checked

2 answers

2


You have a problem with your code relative to the selectors when using ^= to catch name's started by the string Tipo.

Look at these two lines:

$("input[name^='Tipo1']")
$("input[name^='Tipo']")

The second line will catch also the elements that begin with the name Tipo1, because they also start with the string Tipo.

In your case, to pick up the elements by name no need to use selector ^=, just pick up by name in the form of an array adding the square brackets, thus:

$("input[name='Tipo1[]']")
$("input[name='Tipo[]']")

Do this also with other selectors.

Another thing is the function of .each of the checked elements, that is, in relation to the arrays Miccao[] and Dejeccao[]. Remove from the selector the :checked so that all checkboxes are selected (not only checked). No .push() put a this.checked. When the checkbox is checked .push() will send true, otherwise, false. This way, these two arrays will have the same number of items as the others (by the amount of checkboxes).

For example, if you have 5 rows and you mark the first and third row, the array Miccao[] will be:

[true, false, true, false, false]

Both .each will stay like this:

var Miccao = [];
$("input[name='Miccao[]']").each(function() {
   Miccao.push(this.checked);
});

var Dejeccao = [];
$("input[name='Dejeccao[]']").each(function() {
   Dejeccao.push(this.checked);
});

In PHP you can go through the arrays handling whatever true in a way and whatever false other’s:

$miccao1 = $miccao ? "Realizado" : "";

and

$dejeccao1 = $dejeccao ? "Realizado" : "";

1

By filtering the checkboxes your arrays will get different amounts. I see two ways to solve this: change your data structure to an object (it will take more work, but it was best) or simply correct the code to get all the checkboxes, but send the correct value.

Assuming that it is the second alternative that is in the scope of the question, swap checkboxes lines such as

$("input[name^='Dejeccao']:checked").each(function() {Dejeccao.push(this.value)});

For

$("input[name^='Dejeccao']").each(function() {Dejeccao.push(this.prop("checked"))});

Browser other questions tagged

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