Export to .csv from Table

1

I am currently trying to do a job for a friend, but I can not do the following. I have a table where everything is in the database. And the code of that page is this (Ask for a connection that works): index.php

<?php
	require('conexion.php');
	
	$query="SELECT *  FROM umg511_tbl";

	$resultado=$mysqli->query($query);
	
?>

<html>
	<head>
		<title>Usuarios</title>
<style type="text/css">


/* Datagrid */
	body {
  font: normal medium/1.4 sans-serif;
  background: linear-gradient( 0deg, #C0C0C0   , #F8F8F8);}
table {
  border-collapse: collapse;
  width: 100%;
}
th, td {
  padding: 0.25rem;
  border: 1px solid #ccc;
}
tbody tr:nth-child(odd) {
  background: #eee;
}
.centro{
  padding: 0.5rem;
  background: #484848 ;
  color: white;
  text-align: center;
  font-size: 21px;

}

#cuadro{
	width: 90%;
	background: #F8F8F8 ;
	padding: 25px;
	margin: 5px auto;
	border: 3px solid #D8D8D8;
}
#titulo{
	width: 100%;
	background: #282828;
	color:white;

}
	</style>
	</head>
	<body>
	<div id="cuadro">
		<div id="titulo">
		<center><h1>Regristos</h1></center>
		</div>
		
		<table>
			<thead>
				<tr class="centro">
					<td>ID</td>
					<td>Dia</td>
					<td>Descargar</td>
				</tr>
				<tbody>
					<?php while($row=$resultado->fetch_assoc()){ ?>
						<tr>
							<td name="id">
								<center> <?php echo $row['umg511_id']; ?> </center>
							</td>
							<td name="fecha">
								<center><?php echo $row['umg511_day'];?></center>
							</td>
							<td name="descargar">
								<form action="hola.php" method="post" id="enviar">
									<center><input type="submit" value="Descargar" /></center>
								</form>
							</td>
						</tr>
					<?php } ?>
				</tbody>
			</table>	
			</center
		</div>
		</body>
	</html>	
	

What I would like to do is that when I click on the download button, I would pick up the ID and look in the database that matches that id and go down the correct row. I've looked at some posts here, but none of them help me (I tried to follow the one with a select, but I can not adapt it here).

I add the php to export to csv: hello.php

<?php
if (isset($_POST['id'])) {

$list = null;
$dbname = "umg511";
$host = "localhost";
$user = "XX"
$pass = "XX"

try     
 {
 // Include globals from credentials.
 //global $dbname, $host, $user, $pass;

// Set up on database switch
$conn = new PDO("mysql:dbname=$dbname;host=$host", $user, $pass);
$conn->exec("SET CHARACTER SET utf8");


        } catch(PDOException $e) {
            echo $e->getMessage();
                                }

 // Define and perform the SQL SELECT query
  $sql = 'SELECT umg511_text FROM umg511_tbl';
  $result = $conn->query($sql);

 // If the SQL query is succesfully performed ($result not false)
  if($result !== false) 
  {
    $num_fields = mysql_num_fields($result);
    $headers = array();

    for ($i = 0; $i < $num_fields; $i++) {
    $headers[] = mysql_field_name($result , $i);             
    $fp = fopen('php://output', 'w');

    if ($fp && $result) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="export.csv"');
        header('Pragma: no-cache');
        header('Expires: 0');
        fputcsv($fp, $headers);

        while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
        }

        $conn = null;        // Disconnect
        die;
    }
   }
 }
}
}
?>
    
asked by Pepe Flanco 24.05.2017 в 14:12
source

2 answers

1

You could try this, in this part of the code:

            <?php while($row=$resultado->fetch_assoc()){ 
            $datos = serialize($row);//Serializamos la columna
            $dato64 = base64_encode($datos);//La pasamos a base 64    
            ?>
                <tr>
                    <td name="id">
                        <center> <?php echo $row['umg511_id']; ?> </center>
                    </td>
                    <td name="fecha">
                        <center><?php echo $row['umg511_day'];?></center>
                    </td>
                    <td name="descargar">
                        <form action="hola.php" method="post" id="enviar">
                            <center><input type="submit" value="Descargar" /></center>
                            <textarea style="display:hidden" name="resultado">'.$dato64.'</textarea>//Añadimos la columna en un textarea oculto
                        </form>
                    </td>
                </tr>
            <?php } ?>

Adding these lines will pass the row complete encoded to hello.php .

Now the export part:

$row= unserialize(base64_decode($_POST['resultado']));
header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-type:   application/x-msexcel; charset=utf-8");
header("Content-Disposition: attachment; filename=Documento.xls"); 
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); 
            <table>
                <tr>
                    <td name="id">
                        <center> <?php echo $row['umg511_id']; ?> </center>
                    </td>
                    <td name="fecha">
                        <center><?php echo $row['umg511_day'];?></center>
                    </td>           
                </tr>
            </table>

Initially with this you should pass the data of your main php to the one that exports and display the data correctly. If you want to prove that the data arrives, I recommend you comment on header and do:

var_export($row);

And if you want to prove that you export correctly you can leave the headers and create a html table without php (with handwritten data).

I also add a question that I did in which the subject of serializing and coding is better explained in case something fails you: Unserialize multidemensional array in PHP

If in the first query you receive the text in the second php in theory you do not need to execute any query, I do not know how you have organized the array with the results.

    
answered by 24.05.2017 / 15:18
source
0

In the form use a hidden input with the id.

<input name="idOculto" id="idOculto" type="hidden" value="<?php echo $row['umg511_id']; ?>" />

Then when you retrieve the data from the form you only have to do:

$idDescargar = $POST['idOculto'];

The part of obtaining it from the DB will depend on how you have the connections and the Data access layer. Then you just have to download the data in the format you need.

    
answered by 24.05.2017 в 14:19