简体   繁体   English

使用 php y mysql 将数据从表导出到带有复选框的 .csv 文件

[英]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.我正在尝试将复选框中标记的表中的数据导出到 .csv 文件,但每次导出数据时,导出的数据都与表头相同。 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这是 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.这是 csv 文件中的结果。 For this example I have checked 3 columns csv file example对于此示例,我检查了 3 列csv 文件示例

You have a logical error in the code.您的代码中有逻辑错误。

Your foreach loop needs to end before the fseek command.您的foreach循环需要在fseek命令之前结束。 Otherwise, for every value in the "casilla" array it will return to the start of the data and output all of it again.否则,对于“casilla”数组中的每个值,它将返回到数据的开头并再次输出所有数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM