'Export data from a table to a .csv file with a checkbox using php y mysql

I am trying to export data from a table marked in a checkbox to a .csv file but everytime I export the data is exported twice the same as the table headers. I hope you can help me. I am sure I am missing something in the code.

//get records from database
$idusuario = $_SESSION['id_usuario'];
$datos = $mysqli->query("select * from partidas");

if( !isset($_POST['casilla']) OR !is_array($_POST['casilla']) ) {
    exit('No se ha seleccionado ningun dato para la exportacion');
}
    
$delimiter = ",";
$filename = "Partidas_Abiertas" . date('Y-m-d') . ".csv";

//create a file pointer
$f = fopen('php://memory', 'w');
   
//creaa los encabezados de las columnas
$fields = array('Cuenta', 'NombreCliente', 'KZz','zv', 'Doc.Factura', 'Fecha_Factura','Venc.Neto', 'Importe_en_ML', 'texto');
fputcsv($f, $fields, $delimiter);


//extrae cada fila de datos, les da formato csv y los escribe en fichero creado
foreach ($_POST['casilla'] as $value) {

    $value="Select * from partidas where id_partida = $value LIMIT 1"; 
    $result = $mysqli->query($value);

    while($d = $result->fetch_assoc()) {
        $lineData = array($d[cuenta], $d[nCliente], $d[kzz], $d[zv],  $d[docFac], $d[fechaDoc], $d[vencNeto], $d[importe], $d[texto]);
        fputcsv($f, $lineData, $delimiter);
    }

    //vuelve al principio de cada fila
    fseek($f, 0);

    //crea las cabeceras para la exportacion para descarga del archivo con el nombre y fecha
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');


    //Escribe toda la informacion restante de un puntero a un archivo 
    fpassthru($f);
}
exit;
?>

This is the HTML

<p>Resultados <?php echo $datos->num_rows; ?></p>
        
        <div class="row table-responsive">
            <!---Exportar lo marcado en la tabla a csv-----> 
                   <form method="post" action="exportarPartidas.php" method="post">
                        <div class="form-group">
                            <input type="submit" class="btn btn-primary " name="export" value="CSV Export marcado" target="_blank">
                                
                        </div></br> 
            
        <table  class="table display table-striped table-bordered" id="mitabla" border="1" style="width:100%" >
    
            <thead style='background-color:#A0A0A0;'>
            <th align="center"><font color=#070707>Marcar para exportar</th>
            <th align="center"><font color=#070707>N&#186; Cuenta</th>
            <th align="center"><font color=#070707>Nombre de Cliente</th>
            <th align="center"><font color=#070707>Abreviatura (Kzz)</th>
            <th align="center"><font color=#070707>Zona de Ventas</th>
            <th align="center"><font color=#070707>Doc.Fact.</th>
            <th align="center"><font color=#070707>Fecha Factura</th>
            <th align="center"><font color=#070707>Venc. Neto</th>
            <th align="center"><font color=#070707>Importe en ML</th>
            <th align="center"><font color=#070707>Texto</th>
            </thead>
    
        <?php while($d= $datos->fetch_object()):?>
            <tr>
            <td align="center"><input type="checkbox" name="casilla[]" value="<?php echo $d-> id_partida;?>"></td>
            <td align="left"><?php echo $d->cuenta; ?></td>
            <td align="left"><?php echo $d->nCliente;?></td>
            <td align="left"><?php echo $d->kzz;?></td>
            <td align="left"><?php echo $d->zv; ?></td>
            <td align="center"><?php echo $d->docFac; ?></td>
            <td align="center"><?php echo $d->fechaDoc; ?></td>
            <td align="center"><?php echo $d->vencNeto; ?></td>
            <td align="left"><?php echo $d->importe; ?></td>
            <td align="left"><?php echo $d->texto; ?></td>
        
            </tr>
    
        <?php endwhile; ?>
        </table>
      </form>  
            <?php else:?>
                <h3>No hay Datos</h3>
            <?php endif; ?>
    
        </div> 

And this is the result in the csv file. For this example I have checked 3 columnscsv file example



Solution 1:[1]

You have a logical error in the code.

Your foreach loop needs to end before the fseek command. Otherwise, for every value in the "casilla" array it will return to the start of the data and output all of it again.

It should be like this:

//extrae cada fila de datos, les da formato csv y los escribe en fichero creado
foreach ($_POST['casilla'] as $value) {

    $value="Select * from partidas where id_partida = $value LIMIT 1"; 
    $result = $mysqli->query($value);

    while($d = $result->fetch_assoc()) {
        $lineData = array($d[cuenta], $d[nCliente], $d[kzz], $d[zv],  $d[docFac], $d[fechaDoc], $d[vencNeto], $d[importe], $d[texto]);
        fputcsv($f, $lineData, $delimiter);
    }
}
//vuelve al principio de cada fila
fseek($f, 0);

//crea las cabeceras para la exportacion para descarga del archivo con el nombre y fecha
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');


//Escribe toda la informacion restante de un puntero a un archivo 
fpassthru($f);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ADyson