How to save selected and unselected checkboxes

0

I put them a bit in context, I'm doing an academic attendance record system, and I plan to keep the id of the students in a table along with a value that tells me whether or not they attended classes so that after this a percentage of the absences of each student is taken out.

Above they have the table of how it would be approximately, my idea is that the attendees are marked with a check and the absences are left empty and that is sent. Great once said that we go to the code ...

<?php foreach($resultado as $dato): ?>
   <tr>
      <td><?php echo $dato["nombre"] ?></td>
      <td><?php echo $dato["cedula"] ?></td>
      <td><?php echo $dato["acreditable"] ?></td>
  <form action="asistencia_dia.php" method="POST">
      <td><input type="checkbox" name="asistencia[]"></td>
      <input type="hidden" value="<?php echo $dato["id"] ?>" name="estudiante[<?php $dato["id"] ?>]">
   </tr>
<?php endforeach ?>    
  <button type="submit">Enviar</button>
</form>

I explain my disaster a bit: $ result is just a variable which stores a sql sentence, that is supposed to be my form to send 2 data and be able to save them which are the id of each one of the students that are stored in the hidden input and checkboxes.

And he received them this way:

if($_POST){
$estudiante = $_POST["estudiante"];

    echo "<ul>";
    foreach( $_POST["asistencia"] as $asistencia=> $item1)
    {
        echo "<li>";
        echo $item1; 
        echo "</li>"; 
        echo $estudiante[$asistencia];
    }
     echo "</ul>";
}

What they see is just a test, I wanted to visualize that according to the check that it is the corresponding id, I still do not get to the part of saving it in the database.

Once said all that My problem is that although I capture when the checkbox is marked and I see it, I do not detect which one I press, I mean, if for example, checkbox 3 should tell me : on 3, but contrary to that he says: on 1 ..

And my goal is to tell me if I only checkbox 1 tell me: On 1, I mean, that was the check one and so on, if I press the first check and the third one, then tell me: On 1 and On 3 ..

For example: Yes = 1 No = 0

Student Assistance José yes Pedro not Maria yes

You should send me like this yes do not yes

But he sends me like this: yes yes no

That would be my problem, thanks in advance to anyone who can help me, and if you have some time to help me with the rest that I explained, that is to say to save in a database who of the students had a check (I mean they attended) and when not and then do the kind of "counting" to know how many absences or the percentage of absences would have much appreciated. I hope I could have explained my problem well.

    
asked by Juan Osio 20.09.2018 в 01:54
source

6 answers

0

You could try placing your code like this:

<form action="asistencia_dia.php" method="POST">
  <?php foreach($resultado as $dato): ?>
     <tr>
        <td><?php echo $dato["nombre"] ?></td>
        <td><?php echo $dato["cedula"] ?></td>
        <td><?php echo $dato["acreditable"] ?></td>
        <td><input type="checkbox" name="asistencia[]"></td>
        <input type="hidden" value="<?php echo $dato["id"] ?>" name="estudiante[<?php $dato["id"] ?>]">
     </tr>
  <?php endforeach ?>    
  <button type="submit">Enviar</button>
</form>

Basically, what we do is to put the label% co_of opening% before form .

Greetings!

    
answered by 20.09.2018 в 02:49
0

I suggest you raise your form, so that each time you CHANGE the status of a CHECKBOX make a submit with the data to update (Student ID and Assistance YES / NO).

It would be something like this:

<?php foreach($resultado as $dato): ?>
   <tr>
      <td><?php echo $dato["nombre"] ?></td>
      <td><?php echo $dato["cedula"] ?></td>
      <td><?php echo $dato["acreditable"] ?></td>

      <td>
        <form action="asistencia_dia.php" method="POST">
          <input type="checkbox" name="asistencia<?php echo $dato["id"]; ?>" onchange="submit()">
          <input type="hidden" value="<?php echo $dato["id"]; ?>" name="estudiante<?php echo $dato["id"]; ?>">
        </form>
      </td>
   </tr>
<?php endforeach ?>    

Remember that an input of type checkbox when sent in a submit only arrives if it is marked. If it is not checked, it does not reach the destination defined in action.

    
answered by 20.09.2018 в 06:08
0

The option that you are given to submit for each check is good, up to a point, since there will be many requests depending on the number of students.

I leave you with another option that might work:

First:

<form action="asistencia_dia.php" method="POST">
   <?php foreach($resultado as $dato): ?>
       <tr>
          <td><?php echo $dato["nombre"] ?></td>
          <td><?php echo $dato["cedula"] ?></td>
          <td><?php echo $dato["acreditable"] ?></td>
          <td>
              // Aquí concatenamos el id del alumno al nombre del check
              // para poder identificarlo sin problema cuando se envie
              <input type="checkbox" name="asistencia-<?= $dato["id"]; ?>">
              <input type="hidden" value="<?= $dato["id"]; ?>" name="estudiantes[]">
         </td>
       </tr>
   <?php endforeach ?>    
   <button type="submit">Enviar</button>
</form>

Then: On the server side we do the following to process the assistance.

if($_POST){
    // Se obtiene el array(lista) de alumnos
    $estudiantes = (array)$_POST["estudiantes"];

    echo "<ul>";
    foreach( $estudiantes as $estudiante){
       echo "<li>";
       echo 'Alumno: ' . $estudiante;
       // Comprobamos si el alumno tiene asistencia o no
       // Recuerda concatenar la palabra asistencia-, con el id del alumno
       // para hacer referencia al check correcto
       $asistencia = $_POST["asistencia-" . $estudiante] == 'on' ? "Si" : "No";
       echo " Asistió:" . $asistencia;
       echo "</li>"; 
    }
    echo "</ul>";
}

And that would be it.

NOTE: the previous example I could not test, but you can try to verify if it works, and if you make an error or doubt just let it know.

    
answered by 20.09.2018 в 06:46
0

Reading in a global way the approach of the problem, it seems to me that you are approaching the solution wrong: you are worrying too much about what the code does each time you press one of the checkboxes.

If you think about it, as I understand it, it is not important to control what happens every time someone checks or unchecks the checkbox.

The usual way to proceed in these cases is to collect the status of the form by clicking on the send button, through a tour of all the checkboxes.

Here is an example.

In it we group all the checkboxes by the same label name (this is useful when we have in a form only a certain group of elements that we want to reach ... they can also be grouped by classes).

In addition, we use the value tag of the checkbox to store the student's id.

You will see that the code builds an organized object where each pair of elements are the student's id and checkbox status, just the information you need to work on the server .

Then you send that object to the server, crumble it and use it to insert it or whatever it takes.

This is the code:

$("#btnEnviar").click(function() {
  var arrTodo = new Array();
  /*Agrupamos todos los input con name=cbxEstudiante*/
  $('input[name="cbxEstudiante"]').each(function(element) {
    var item = {};
    item.id = this.value;
    item.status = this.checked;
    arrTodo.push(item);
  });

  /*Creamos un objeto para enviarlo al servidor*/
  var toPost = JSON.stringify(arrTodo);
  console.log(toPost);
  
  /*
    Aquí convendría lanzar una petición Ajax al servidor
    enviándole la variabel toPost
    En el servidor desglosamos esa variable
    obteniendo cada id y cada estatus y procesamos los datos
  */

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table is-striped">
  <theader>
    <th>Nombre</th>
    <th>Estatus</th>
  </theader>
  <tbody>
    <tr>
      <td>Pedro</td>
      <td>
        <input type="checkbox" name="cbxEstudiante" value="1" /></td>
    </tr>
    <tr>
      <td>Santiago</td>
      <td>
        <input type="checkbox" name="cbxEstudiante" value="2" /></td>
    </tr>
    <tr>
      <td>María</td>
      <td>
        <input type="checkbox" name="cbxEstudiante" value="3" /></td>
    </tr>
    <tr>
      <td>Juan</td>
      <td>
        <input type="checkbox" name="cbxEstudiante" value="4" /></td>
    </tr>
    </tbody>
    </table>
    <a class="button is-primary" id="btnEnviar">Enviar</a>

To the server you will be sending an ordered object, which you can convert into an array to work in an equally ordered and transparent way:

[{
    "id": "1",
    "status": true
}, {
    "id": "2",
    "status": false
}, {
    "id": "3",
    "status": true
}, {
    "id": "4",
    "status": false
}]

I hope you find it useful.

    
answered by 20.09.2018 в 08:34
0

I propose the solution similar to that of Jesus Magallon.

<?php 
$resultado = [
    ['id'=>1,'nombre'=>'Fabio',   'cedula'=>'c1','acreditable'=>''],
    ['id'=>2,'nombre'=>'Ernesto', 'cedula'=>'c2','acreditable'=>''],
    ['id'=>5,'nombre'=>'Marcos',  'cedula'=>'c5','acreditable'=>''],
    ['id'=>9,'nombre'=>'Saul',    'cedula'=>'c9','acreditable'=>''],
    ['id'=>7,'nombre'=>'Jeronimo','cedula'=>'c7','acreditable'=>''],
    ['id'=>3,'nombre'=>'Raul',    'cedula'=>'c3','acreditable'=>''],
];
?>

<form action="asistencia_dia.php" method="POST">'

<?php foreach($resultado as $dato): ?>
     <tr>
        <td><?php echo $dato["nombre"] ?></td>
        <td><?php echo $dato["cedula"] ?></td>
        <td><?php echo $dato["acreditable"] ?></td>
        <td><input type="checkbox" name="asistencia[]" value="<?php echo $dato["id"] ?>"></td>
     </tr>
  <?php endforeach ?>    
  <button type="submit">Enviar</button>
</form>

You really would not need the hidden input, since the checkbox itself has a value, the student id.

In the asistencia_dia.php file, an array with index asistencia will arrive in the $ _POST, and with values the ids of those that are marked. With which you know WHO has attended. Already in your bbdd update those ids with assistance = true or whatever in your data model.

    
answered by 20.09.2018 в 10:11
0

Thank you very much for taking the time and providing me with various answers, in the end it occurred to me the simple fact that instead of saving if the checkbox was empty or not ( EYE THIS IS KEPT ONLY WHEN PRESSING THE BUTTON SEND, ONLY IN MANY PHOTOS WITHOUT WANTING TO CUT IT ), just create an event in Javascript that will change the value of a hidden input every time your checkbox is pressed

That is to say: There will be a default hidden input with the value of 1 and each time the corresponding checkbox is pressed, then I change the value to 2, thus determining the number 1 that the student did not attend and with the number 2 that the student did attend classes. And in this way I keep it in the database.

I do not know if it will be the best solution or if it will bring problems later, but for now it works, thank you very much again for all of your answers.

    
answered by 21.09.2018 в 21:06