get column names when exporting from mysql to csv using PHP - php

I am trying to export a table from a mysql db to csv.I am able to do this successfully,however, it doesnt export the column names,is there any way i achieve this?Some pointers would be great.Please check out my data_export.php file below:
<?php
include 'class.user.php';
$conn=mysqli_connect("localhost","root","PASSWORD","reflective");
#declare the school variable for use in the select* query
$school = $_POST['school'];
#query the students table for data to export
$select="SELECT * FROM students WHERE school_id ='$school'";
$result = mysqli_query($conn, $select);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_num_fields($result);
$headers ="";
while ($property = mysqli_fetch_field($result)) {
$headers.= $property->name.",";
}
$headers.="\n";
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="students_data.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
?>

I would suggest you use the array_keys() method in PHP. It will extract all the keys from the array you fetch from the database. You just need to pass the first array as argument in the method like this,
array_keys($data[0]);

Related

Issue forcing download of CSV File | PHP

Essentially I have the following script that should interpret the data from the query, format as CSV and download the CSV file.
While the data and CSV structure is being generated correctly, the file is not downloading. Instead the data is just being presented on the web page:
<?php
//Our MySQL connection details.
$host = '';
$user = '';
$password = '';
$database = '';
//Connect to MySQL using PDO.
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
//Create our SQL query.
$sql = " ";
//Prepare our SQL query.
$statement = $pdo->prepare($sql);
//Executre our SQL query.
$statement->execute();
//Fetch all of the rows from our MySQL table.
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
//Get the column names.
$columnNames = array();
if(!empty($rows)){
//We only need to loop through the first row of our result
//in order to collate the column names.
$firstRow = $rows[0];
foreach($firstRow as $colName => $val){
$columnNames[] = $colName;
}
}
//Setup the filename that our CSV will have when it is downloaded.
$fileName = 'mysql-export.csv';
//Set the Content-Type and Content-Disposition headers to force the download.
header('Content-Type: application/csv');
header("Content-Disposition: attachment; filename=mysql-export.csv");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/octet-stream");
header("Content-type: application/force-download");
//Open up a file pointer
$fp = fopen('php://output', 'w');
//Start off by writing the column names to the file.
fputcsv($fp, $columnNames);
//Then, loop through the rows and write them to the CSV file.
foreach ($rows as $row) {
fputcsv($fp, $row);
}
//Close the file pointer.
fclose($fp);
The headers should be:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="mysql-export.csv"');
Note that it's "text/csv", not "application/csv". And you shouldn't need the other two (application/octet-stream and application/force-download). I hope that helps.

Escaping php '#' comment symbol in mysql database when exporting to csv

I have a php script that exports a mysql database table to a csv file. For one of the fields of data, a user included an octothorp # in their text. For example, My Idea #1.
When my code gets to this piece of data, it stops at the # symbol. I'm guessing it hits the # and believes everything else that follows is a comment.
As a temporary solution, I am stripping out this symbol when adding the data to the database, but this is not ideal. Given the script below, how might I escape this symbol to prevent this from happening?
$query = "SELECT * FROM my_table";
$result = #mysqli_query($dbc, $query);
if (!$result) {
die('Couldn\'t fetch records');
}
$num_fields = mysqli_num_fields($result);
$headers = [];
for ($i = 0; $i < $num_fields; $i++) {
$field = mysqli_fetch_field_direct($result, $i);
// var_dump($field);
$headers[] = $field->name;
}
$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 = mysqli_fetch_array($result, MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}

I want to save table in a cell of CSV but changing line automatically in case of large table

![I want to save table in a cell of CSV but changing line automatically in case of large table
thanks in advance
code to write CSV`
when I export csv of scraped data it messed up when table contains large number of rows or tr's please help me out of this.
`
$fp = fopen('stream.csv', "w");
foreach ($output as $row) {
fputcsv($fp, $row);
}
fclose($df);
fclose($fp);
Question is really not clear enough but here is how I generate my CSV files. Good thing is that it also shows column names automatically.
$result = mysqli_query ($mysqliConn,"SELECT * FROM core ORDER BY start_datetime ASC");
$fields = mysqli_fetch_fields($result);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_fetch_fields($result);
$headers = array();
foreach ($fields as $field) {
$headers[] = $field->name;
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="core.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
Hope this helps.

csv php mysql data export - all data is being exported in one column

I need Name,Given phonenumber mobile notes location to all be in separate columns on my csv export using the php script below. The current code exports all of the selected data in one column for each record. Thank you!
$result = mysql_query('SELECT who as "Name,Given" , phonenumber as "mobile", notes, location FROM `phpbb_phonelist` WHERE `activenumber` = 1');
if (!$result) die('Couldn\'t fetch records');
$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="phonelist.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
Use this code
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);

Generating excel sheet from MySql database using PHP

I'm new to PHP. I'm using the following code to generate an excel sheet from Mysql database using PHP.
<?php
include("../Connection/Connection.php");
$db_con=new Connection();
$db_con->get_connection(); //Opens a database connection. This function is contained in the Connection.php which is included above.
$result = mysql_query("SELECT * FROM country");
if (!$result) die('Couldn\'t fetch records');
$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 = mysql_fetch_array($result))
{
fputcsv($fp, array_values($row));
}
die;
}
?>
The above code is working and it generates the specified file export.csv but the problem is that it generates each column from MySql in this file twice. In other words, each column is duplicated twice (headers displayed are not duplicated though). What is wrong with this code? What changes should be made so that it displays each column exactly once?
Use mysql_fetch_row instead.
mysql_fetch_array fetches an array with BOTH string indexes and numeric indexes, so each value is fetched twice. Your code would work with either mysql_fetch_assoc or mysql_fetch_row.

Categories