How to assign dynamic ids

2

How can I assign a dynamic id to a button that I print in a while? I need to assign a dynamic id to make the insertion, since I do not have a form.

here the code

        while($fila=$consulta->fetch(PDO::FETCH_ASSOC)){
             $this->empleados[]=$filas;
             $Filas = consult_cedula($fila['Persona']);

             echo "<tr>";
             echo '<td>' . $Filas['codsucursal'] . '</td>';
             echo '<td>' . $fila['Persona'] . '</td>';
             echo '<td>' . $fila['Fecha'] . '</td>';
             echo '<td>' . $fila['Hora'] . '</td>';
             echo '<td>' . $Filas['nombre'] . '</td>';
             echo '<td>' . $Filas['cargo'] . '</td>';

             echo '<td>' . '<input type="button" class="btn btn-danger" id="btn" value="..." data-fech="' .
             $fila['Fecha'] . '" data-hora="' . $fila['Hora'] . '" data-ced="' . $fila['Persona'] .
             '" data-nom="' . $Filas['nombre'] . '" data-cargo="' . $Filas['cargo'] . '">';
             echo "</tr>";
    
asked by Jdavid Barajas 07.05.2018 в 17:50
source

1 answer

1

As already said in comments, you can use a counter, in this case $i , that you initialize to 1 before entering the while , using that value to give the id to the button in each step of the loop.

Also, you can give more clarity to your code by using a variable that concatenates the content you want to show, and doing echo of that variable only at the end. In the same way, it could give more clarity to the code to use variables for the different values that you present in the table, much more if some of those values are used more than once.

The code would look like this:

/*Variable única para ir concatenando todo el contenido HTML*/
$strHTML="";
/*Contador que se irá incrementando*/
$i = 1;

while ($i <= 10) {
    $strHTML.="<tr>";
    $codSucursal=$Filas['codsucursal'];
    $persona=$fila['Persona'];
    $fecha=$fila['Fecha'];
    $hora=$fila['Hora'];              
    $nombre=$Filas['nombre'];
    $cargo=$Filas['cargo'];

    $strHTML.="<td>$codSucursal</td>";
    $strHTML.="<td>$persona</td>";
    $strHTML.="<td>$fecha</td>";
    $strHTML.="<td>$hora</td>";
    $strHTML.="<td>$nombre</td>";
    $strHTML.="<td>$cargo</td>";
    $strHTML.="<td>".'<input type="button" class="btn btn-danger" id="btn-'.$i.'" value="..." 
               data-fech="' .$fecha . '" data-hora="' . $hora . '" data-ced="' . $persona .
               '" data-nom="' . $nombre . '" data-cargo="' . $cargo . '"></td>';
    $strHTML.= "</tr>";
    $i++;
}
/*Imprimimos una sola vez el contenido*/
echo $strHTML;
    
answered by 08.05.2018 в 00:53