Outputting Column titles in CSV Export - php

I have this query that exports to a csv file. It works fine the only thing i can't figure out is i need to export the column titles as well, and have them display as Full Name, UserName, Flag and Reason. Below is the code and it exports all the rows fine but I'm not sure how to export the column titles above the respected rows.
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=blackflag_bidders.csv");
header("Pragma: no-cache");
header("Expires: 0");
//SQL Query for Data
$sql = "SELECT ui.first_name, ui.last_name, u.username,
if(u.flag=1,'BLK', if(u.flag=2,'NAA','')) flag,
if(u.flag!=0, IFNULL(ui.note,''),'') reason
FROM user u
LEFT JOIN user_info ui ON ui.user_id=u.id
WHERE u.flag!=0;";
//Prepare Query, Bind Parameters, Excute Query
$STH = $sam_db->prepare($sql);
$STH->execute();
//Export to .CSV
$fp = fopen('php://output', 'w');
//fputcsv($fp);
while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
fclose($fp);

One way would be to fetch the first result by associative, those associative indices are columns anyway. Apply array_keys to get those, then first add the headers, then the first fetched row, then loop the rest.
// first set
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
// $headers = array_map('ucfirst', $headers); // optional, capitalize first letter of headers
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row
while ($row = $STH->fetch(PDO::FETCH_NUM)) {
fputcsv($fp,$row); // push the rest
}
fclose($fp);

The answer to this will depend upon whether you already know the column names or not. It seems like you do (e.g. you are already calling 'Select ui.firstname...')
If you do not, you can get the names by looking at this thread:
What is the Select statement to return the column names in a table
Once you have the names, you simply need to create a single row with the names and add them to file by modifying your code as:
//Export to .CSV
$columnNamesRow = "FirstName, LastName, UserName";
$fp = fopen('php://output', 'w');
fputcsv($fp, $columnNamesRow);
//fputcsv($fp);
while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
fclose($fp);

You can get a column in CSV by simply displaying your results in Tabular form here in the page using <table> tag of HTML.
$result = "<table>";
while ($row = $STH->fetch(PDO::FETCH_NUM)){
$result .= "<tr><td>$row1</td><td>$row2</td><td>$row3</td></tr>";
}
$result .= "</table>";
fputcsv($fp, $result);
By $row1, $row2, I mean the values you get in your resultset

Related

My export file doesn't contain column names [duplicate]

I am in need of a way to export my MYSQL Database to CSV via PHP, but I need to select the column names as well. So Far I have the following which does everything I need except get the column names.
echo "Export Starting \n";
$SQL = ("SELECT *
FROM INF_TimeEntries
WHERE Exported IS NULL");
$result = mysqli_query($db_conn, $SQL) or die("Selection Error " . mysqli_error($db_conn));
echo "Export Data Selected \n";
$fp = fopen('../updateDatabase/timesheetExport/TimeEntries.csv', 'w');
echo "Starting Write to CSV \n";
while($row = mysqli_fetch_assoc($result)){
fputcsv($fp, $row);
$RowID = $row['ID'];
$exportTime = date("Y-m-d H:i:s");
$sql = ("UPDATE INF_TimeEntries
SET Exported = '$exportTime'
WHERE ID = '$RowID'");
if ($mysqli_app->query($sql) === TRUE) {
}
else {
echo date("Y-m-d H:i:s")."\n";
echo "An Error Occured please contact the administrator ". $mysqli_app->error."\n";
}
}
echo "Export Completed \n";
fclose($fp);
mysqli_close($mysqli_app);
mysqli_close($db_conn);
I am not sure how I would go about Achieving this. I do not simply need to get column names but Column names and the data contained in each of these columns. I have not found any information on this in the other question suggested.
Since you're using mysqli_fetch_assoc, the name of the columns are the keys of the $row array in each iteration. You can put that in the file in the first iteration:
echo "Starting Write to CSV \n";
$first = true;
while($row = mysqli_fetch_assoc($result)){
if ($first) {
fputcsv($fp, array_keys($row));
$first = false;
}
fputcsv($fp, $row);
// ..
}
Once you have your $result set from your mysqli_query() method, you can use mysqli_fetch_fields() to return an array of descriptions of the columns in the result set.
Each element of that array is a an object with several properties. One property is name -- which you can use as a header for your csv file. You also get properties like max_length, length, and table. The linked documentation shows an example of using this metadata.
This metadata is especially useful if you have a query more complex than SELECT * FROM table: if you assign aliases to the columns in your query, they show up in the name properties of the metadata array elements.
This works even if the result set has no rows in it.
Sounds pretty simple, as long as everything else is already working for you. You can create an array with the column names, and fputcsv($fp, $array_of_column_names) right before your while loop.

CSV Export: Multiple Database Rows to Single Row

Hi,
The problem: I Have an Export from a Database, however it needs to extract data from two tables. I Achieve this with an inner join.
artikel is the table with the basic information. It contains the id, article number, name, type and package form.
article_content is the table which contains the text which is part of the article, however, there are multiple languages. Every Article has a row for each language.
The Export Code
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=artikeldatenbank-' . date("dmyhi") . '.csv');
$output = fopen('php://output', 'w');
$stmt = $db->prepare('SELECT artikel.id, artikel.artikel_nummer, artikel.artikel_name, artikel.artikel_packung, artikel.artikel_cat, article_content.article_text, article_content.article_recuse, article_content.article_spec FROM artikel INNER JOIN article_content ON article_content.article_id = artikel.artikel_nummer');
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
fputcsv($output, $row);
What I want to Achieve
I need every row from the article_content table by it's article in a single line, instead of multiple lines. Sorry for the links, but imgur doesn't let me upload these. (Don't know why)
What happens now (image): http://prntscr.com/ek86bn
What I Want (edited image): http://prntscr.com/ek87ct
What is the best way to achieve this? Is this possible on the way I do it now?
Skip the VIEW solution, Solve it by code, my suggestion is
$result = $stmt->get_result();
$artikeID = '';
$newRow = [];
while ($row = $result->fetch_assoc())
{
if($artikeID != $row['id'])
{
if(!empty($newRow))
{
fputcsv($output, $newRow);
$newRow = [];
}
$artikeID = $row['id'];
$newRow = $row;
}
else
{
$newRow['title-'.$row['id']] = $row['artikel_name'];
$newRow['content-'.$row['id']] = $row['article_text'];
}
}

Use PHP to get Column Names and Data for CSV export (MYSQL)

I am in need of a way to export my MYSQL Database to CSV via PHP, but I need to select the column names as well. So Far I have the following which does everything I need except get the column names.
echo "Export Starting \n";
$SQL = ("SELECT *
FROM INF_TimeEntries
WHERE Exported IS NULL");
$result = mysqli_query($db_conn, $SQL) or die("Selection Error " . mysqli_error($db_conn));
echo "Export Data Selected \n";
$fp = fopen('../updateDatabase/timesheetExport/TimeEntries.csv', 'w');
echo "Starting Write to CSV \n";
while($row = mysqli_fetch_assoc($result)){
fputcsv($fp, $row);
$RowID = $row['ID'];
$exportTime = date("Y-m-d H:i:s");
$sql = ("UPDATE INF_TimeEntries
SET Exported = '$exportTime'
WHERE ID = '$RowID'");
if ($mysqli_app->query($sql) === TRUE) {
}
else {
echo date("Y-m-d H:i:s")."\n";
echo "An Error Occured please contact the administrator ". $mysqli_app->error."\n";
}
}
echo "Export Completed \n";
fclose($fp);
mysqli_close($mysqli_app);
mysqli_close($db_conn);
I am not sure how I would go about Achieving this. I do not simply need to get column names but Column names and the data contained in each of these columns. I have not found any information on this in the other question suggested.
Since you're using mysqli_fetch_assoc, the name of the columns are the keys of the $row array in each iteration. You can put that in the file in the first iteration:
echo "Starting Write to CSV \n";
$first = true;
while($row = mysqli_fetch_assoc($result)){
if ($first) {
fputcsv($fp, array_keys($row));
$first = false;
}
fputcsv($fp, $row);
// ..
}
Once you have your $result set from your mysqli_query() method, you can use mysqli_fetch_fields() to return an array of descriptions of the columns in the result set.
Each element of that array is a an object with several properties. One property is name -- which you can use as a header for your csv file. You also get properties like max_length, length, and table. The linked documentation shows an example of using this metadata.
This metadata is especially useful if you have a query more complex than SELECT * FROM table: if you assign aliases to the columns in your query, they show up in the name properties of the metadata array elements.
This works even if the result set has no rows in it.
Sounds pretty simple, as long as everything else is already working for you. You can create an array with the column names, and fputcsv($fp, $array_of_column_names) right before your while loop.

creating a CSV file from MySQL Table data in PHP

I have this code in PHP:
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=calls.csv');
// create a file pointer connected to the output stream
$output = fopen($_SERVER["DOCUMENT_ROOT"].'/file_dump/price_tariffs/calls.csv', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2'));
// loop over the rows, outputting them
$sql="SELECT * from call_costs where sequence < '50' ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_array($rs)) {
fputcsv($output, $result["number"]);
}
its creating the file name calls.csv in the price_tariffs directory but its only adding the column 1 and column 2 and not the data from the while loop
i have check the loop and echoed data inside the loop which displays fine
fputcsv takes the second parameter as an array(), "and you already used fputcsv outside of the loop passing the second param as an array"[*] with two values inside.
Try to do the same inside your loop:
fputcsv($output, array($result["number"], $result["somethingelse"]));
[*]: edited, added enquoted sentence after clarifying in the comments below.
Select only the columns that you want:
$sql = "SELECT column1, column2 FROM call_costs WHERE sequence < '50'";
Then use mysql_fetch_assoc() to fetch each row as an associative array, and output that:
$rs=mysql_query($sql,$conn);
while($row = mysql_fetch_assoc($rs)) {
fputcsv($output, $row);
}
fputcsv()'s second argument is supposed to be an array of the values that should be put into fields in the CSV file.
since you're sending the data to the client directly, you should echo it instead of saving it to a file :) Open the php://output instead:
Try this (from powtacs answer:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=calls.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'));
// loop over the rows, outputting them
$sql="SELECT * from call_costs where sequence < '50' ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_assoc($rs)) {
fputcsv($output, $result);
}
Also please note that mysql is depreciated, and you should use mysqli or PDO instead
Checkout the mysql_fetch_array in the php manual, so, we can say:
...
while($result = mysql_fetch_array($rs,MYSQL_NUM)) {
fputcsv($output, $result);
}
Just add the second optional parameter MYSQL_NUM to return numerical array and supply all of it as a parameter in fputcsv. By this way you will get all the raw's fields data in your csv file.

Exporting data from database to csv file using php

I am able to export database to csv but my code somehow imports twice the data to my csv file. I.e same column twice side by side.this is my code. I think my problem is with the implode statment. Any help would be appreciated.
<?php
$db = new sqlite3('I:\preethi\webbs.db');
$headers = array
('Id','CompanyId','DateTime','Serial','DeviceId','AgentAId','GpsAddress','Targa','CommonRoadDescription'
,'RoadCivicNumber','VehicleBrandDescription','VehicleModelDescription' ,'VerbaliVehicleTypeDescription','CommonColorVehicleDescription','VerbaliRuleOneCode','VerbaliRuleOneDes
cription','VerbaliRuleOnePoints'
,'VerbaliClosedNoteDescription','Points','VerbaliMissedNotificationDescription
','MissedNotificationNote','StatementNote');
$results = $db->query('select'.implode (',',$headers).'from VerbaliData');
//$results = $db->query( 'select
Id ,CompanyId ,DateTime ,Serial ,DeviceId ,AgentAId
,GpsAddress ,Targa ,CommonRoadDescription ,RoadCivicNumber ,VehicleBrandDescription
,VehicleModelDescription ,VerbaliVehicleTypeDescription ,CommonColorVehicleDescription
,VerbaliRuleOneCode ,VerbaliRuleOneDescription ,VerbaliRuleOnePoints ,VerbaliClosedNoteDescription
,Points ,VerbaliMissedNotificationDescription ,MissedNotificationNote ,StatementNote from
VerbaliData');
$fp = fopen('explores.csv', 'w');
fputcsv($fp,$headers);
while ($row = $results->fetchArray()) {
fputcsv($fp, $row);
}
fclose($fp);
?>
Just try with :
while($row = $results->fetchArray(SQLITE3_NUM)) {
Or
while($row = $results->fetchArray(SQLITE3_ASSOC)) {
More Details: http://php.net/manual/en/sqlite3result.fetcharray.php
You have a slight prob in your code fetchArray() returns two array sets one associative and one is numbered, use fetchArray(SQLITE3_NUM) or fetchArray(SQLITE3_ASSOC).

Categories