fputcsv - columns from table displayed in one column - php

I have a problem with putting data from mysql database to csv file. The column headers are ok but rest of rows from table are in one column. Please help..
<?php
$con=mysqli_connect("localhost","asasdd","asasdasd","asdasd");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
$array = array("Id;Imie_i_nazwisko;Nazwa_kursu;Data_kursu");
$array = str_replace('"', '', $array);
fputcsv($output, $array);
$rows = mysqli_query($con, 'SELECT * FROM kursanci');
while ($row = mysqli_fetch_assoc($rows))
{
fputcsv($output, $row);
}
mysqli_close($con);
?>
Resolved should be like this:
<?php
$con=mysqli_connect("localhost","asd","asd","asd");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
$array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');
fputcsv($output, $array, ';');
$rows = mysqli_query($con, 'SELECT * FROM kursanci');
while ($row = mysqli_fetch_assoc($rows))
{
fputcsv($output, $row, ';');
}
mysqli_close($con);
?>

CSV files expects "," as separator. Only MS-Excel uses ";" as separator by default.
Replace ; for ,, make your array with multiples elements for your header and be happy!
$array = array("Id;Imie_i_nazwisko;Nazwa_kursu;Data_kursu");
$array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');
If you are using MS-Excel and/or need to use ";" as separator, just use this:
$array = array('Id','Imie_i_nazwisko','Nazwa_kursu','Data_kursu');
fputcsv($output, $array, ';');
....
fputcsv($output, $row, ';');
....

Related

Not able to export CSV file from MySQL data by using following code

When I click on button to export file it just redirects to the
export.php file given as href to the button and does nt download the
file
<?php
include 'config.php';
$query = "SELECT d_domain, d_purchase_price, d_selling_price FROM
domains";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$delimiter = ",";
$filename = "data.csv";
$output = fopen('php://memory', 'w');
$fields = array('Domain Name', 'Purchase Price', 'Selling Price');
fputcsv($output, $fields, $delimiter);
while ($row = mysqli_fetch_assoc($result)) {
$lineData = array($row['d_domain'], $row['d_purchase_price'],
$row['d_selling_price']);
fputcsv($output, $lineData, $delimiter);
}
fseek($output, 0);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename= data.csv');
fpassthru($f);
}
Use rewind before seek also in fpassthru($f) you're passing wrong file handle
Try this code
<?php
include 'config.php';
$query = "SELECT d_domain, d_purchase_price, d_selling_price FROM
domains";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$delimiter = ",";
$filename = "data.csv";
$output = fopen('php://memory', 'w');
$fields = array('Domain Name', 'Purchase Price', 'Selling Price');
fputcsv($output, $fields, $delimiter);
while ($row = mysqli_fetch_assoc($result)) {
$lineData = array($row['d_domain'], $row['d_purchase_price'],
$row['d_selling_price']);
fputcsv($output, $lineData, $delimiter);
}
rewind($output);
fseek($output, 0);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename= data.csv');
fpassthru($output); // You're using $f
}
If it still not working then might be some issue with the php://memory usage in your server.. might be it will restricted.. You can also try with php://output this will definitely work
Try this code
<?php
include 'config.php';
$query = "SELECT d_domain, d_purchase_price, d_selling_price FROM
domains";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
$delimiter = ",";
$filename = "data.csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename= data.csv');
$output = fopen('php://output', 'w');
$fields = array('Domain Name', 'Purchase Price', 'Selling Price');
fputcsv($output, $fields, $delimiter);
while ($row = mysqli_fetch_assoc($result)) {
$lineData = array($row['d_domain'], $row['d_purchase_price'],
$row['d_selling_price']);
fputcsv($output, $lineData, $delimiter);
}
//rewind($output);
//fseek($output, 0);
//fpassthru($output); // You're using $f
fclose($output);
}

Create comma delimited .csv file with php

I am trying to:
create comma delimited .csv file with php code.
Insert column name in the first line of the .csv file.
Please advise how can I make this happen.
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".$batch_id.".csv");
header("Pragma: no-cache");
header("Expires: 0");
$conn_sp = mssql_connect("SQLServer", "user", "password");
$db_sp = mssql_select_db("databaseName", $conn_sp);
$stmt = mssql_init("[StoredProcedureName]",$conn_sp);
mssql_bind($stmt, "#BatchNo", $batch_id, SQLVARCHAR, FALSE, FALSE, 20);
$result = mssql_query("SET ANSI_NULLS ON");
$result = mssql_query("SET ANSI_WARNINGS ON");
$result = mssql_execute($stmt);
$record="";
$comma=",";
$record_end="\n";
while ($row = mssql_fetch_array($result, MSSQL_ASSOC)){
foreach ($row as $key => $value) {
echo $value;
}
echo "\n";
}?>
!
Well just look at how a .csv-file is created.
Usually like this:
Delimiter: ,
New line: \n
Enclose entry by: "
e.g.
"r1a","r1b","r1c"
"r2a","r2b","r2c"
etc...
This is how your code should work (untested):
echo '"colname1","colname2",...';
while ($row = mssql_fetch_array($result, MSSQL_ASSOC)){
$first = true;
foreach ($row as $key => $value) {
if(!$first) {
echo ",";
}
echo '"'.$value.'"';
}
echo "\n";
$first=false;
}

while exporting file from database to csv,it gives displays content in the row of table column name

While exporting file to csv,my contents are added in the same row of column names.I want content just below to the respective columns.The code is as follow
<?php
$filename = "file.csv";
$fp = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
$headerLine = 'Sr. No,Name,DOB,Address';
fwrite($fp, $headerLine);
$query = "select * from registratin";
$result = mssql_query($query);
$i = 1;
while($row = mssql_fetch_row($result)) {
$row = array_merge(array($i), $row);
fputcsv($fp, $row);
$i++;
}
?>
You can do it simply as follows , there is no need to array merge
<?php
$filename = "file.csv";
$fp = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
$headerLine = 'Sr. No,Name,DOB,Address';
fputcsv($fp, explode(",",$headerLine); // adding heading
$query = "select * from registratin";
$result = mssql_query($query);
$i = 1;
while($row = mssql_fetch_row($result)) {
//$row = array_merge(array($i), $row); ***no need***
fputcsv($fp, $row);
$i++;
}
fclose($fp);
?>
Its better to use mysqli, and this is the simple way to get the work done.
And in select choose only required columns.
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('SR No', 'Name','DOB','Address'));
$conn = mysqli_connect('localhost', 'root', 'password',"database");
$rows = mysqli_query($conn,'SELECT * from registration');
while ($row = mysqli_fetch_assoc($rows))
fputcsv($output, $row);

How to set up comma delimiter to export each cell from php to csv

I have a php script that exports a data from mysql into the csv. Everything worked fine, when the script was smaller but now, when it reaches a numerous code lines it doesn't do the job.
PROBLEM: it export csv file regularly, but all the tables results are in the first cell of excel. It is supposed to fill each cell - it should recognize in database where there is a comma, then use delimiter and split into cells separately.
So, the delimiter is not working and I don't know why. It should use commas and split it, and it should use | to split again.
This is the code:
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$columnName = array();
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
$columnName[] = $row['Field'];
$i++;
}
}
$columnName[] .= "\n";
$needle = '|';
$values = mysql_query("SELECT * FROM ".$table." where id=".$id."");
while ($rowr = mysql_fetch_row($values))
{
for ($j=0;$j<$i;$j++)
{
$colName = $columnName[$j];
$count = strlen($rowr[$j]) - strlen(str_replace(str_split($needle), '', $rowr[$j]));
if ($count > 1)
{
for($p=0;$p<$count;$p++)
{
$colName .= ",";
}
$columnName[$j] = $colName;
$csv_output_column_names .= $columnName[$j].", ";
$csv_output_column_values .= str_replace('|',',',$rowr[$j]).", ";
}
else
{
$csv_output_column_names .= $columnName[$j].", ";
$csv_output_column_values .= $rowr[$j] .", ";
}
}
$csv_output_column_values .= "\n";
}
$csv_output = $csv_output_column_names."\n".$csv_output_column_values;
$filename = $file."_".date("Y-m-d");
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
Your issue is that you're not quoting fields as Excel expects it.
Instead of reinventing the wheel, you should use the already existing fgetcsv and fputcsv functions.
Normally these are used to write to files, but you can create a file handle to standard out so that they're printed to screen. For example:
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
// $lines is a 2D array with all rows and their column data
// $columns is a 1D array with each row's columns (see examples from fputcsv documentation)
$out = fopen("php://stdout", "w");
foreach ($lines as $columns) { fputcsv($out, $columns); }
fclose($out);
You need to care about memory to begin with, including this solves the problem delimited CSV.
Example:
$file = new SplFileObject('php://output', 'w');
$file->fputcsv($rowr, ';', '"');

Exporting table to CSV via php button

I am really new to php and everything I have learned is from my school textbook and online research. With that said I am trying to complete an assignment and I am stuck on the last part. for the final part the assignment says to "Create a PHP script that will dump the contents of the employee table into CSV text file that has comma separated values for each record. Each new record should begin on a new line". I have tried many online tutorials but none of them teach how to put this event in a button. I am including my code so you can see the mess I have. It's not to bad but I am sure I can do the same task with much less code. Again I am just starting out and this is the best I can do for now. Could anyone give any suggestions on how this could be done. I have my button on line 140. I also used a db_connect() function so i don't have to write it many times. I can peon use this to read the database before I save as a csv.
Any suggestions would be greatly appreciated. Be warned It's a lot of code to follow.
<h2>Employee Search</h2>
<form action="Draft.php" name="dbToCSV" method="GET">
<input type="submit" name="dbToCSV" value="Export Database to CSV" <?php if (isset($_GET['dbToCSV']))
{
//Do this code
}
else
{
echo "Error!";
} ?>><br />
</form>
<form action="Draft.php" method="GET">
By name: <input type="text" name="searchName">
<input type="submit" value="Search Name"><br />
</form>
<form action="Draft.php" method="GET">
By language: <input type="text" name="searchLang">
<input type="submit" value="Search Language"><br />
</form>
It's 2017 and mysqli is more common than mysql now. So here's a mysqli version of Josh Liptzin's answer:
<?php
/* Attempt MySQL server connection. */
$connection = mysqli_connect($database_server, $database_username, $database_password, $database_name);
// Check connection
if($connection === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$query = "SELECT * FROM Employee_data";
$result = mysqli_query($connection, $query);
$number_of_fields = mysqli_num_fields($result);
$headers = array();
for ($i = 0; $i < $number_of_fields; $i++) {
$headers[] = mysqli_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));
}
die;
}
function mysqli_field_name($result, $field_offset)
{
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}
?>
You are literally trying to put the PHP code inside the HTML button. The button can simply be a link to another page (like dump.php), which contains some PHP like the following:
Link:
Download employee data
dump.php:
<?php
$result = mysql_query('SELECT * FROM `employee_data`');
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 = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
?>
Code source: PHP code to convert a MySQL query to CSV
For your own sake you shouldn't copy and paste the above code into your assignment - there's a world of difference between the code you posted and the code above that the grader will instantly pick up on.
So the class is over and I figure I would show how I resolved my issue. this made the most sense to me and it didn't take many lines of code. I am sure there are possibly even shorter ways to do this but for being very new to php i thing I did an ok job with the code.
I basically made an if statement that checks if there are any records in the database then it takes each record field and writes it to the cdv file while adding a comma. I did this code twice. The top code writes the database field names and the second half writes the values in those fields. Thanks for the advice everyone. I am glad I was able to figure it out in time to submit my assignment.
if (isset($_GET['dbToCSV']))
{
// database connection
db_connect();
$query = mysql_query("SELECT * FROM employee_data") or die(mysql_error());
$number_rows = mysql_num_rows($query);
if ($number_rows >= 1)
{
$filename = "exported_db_" . date("m-d-Y_hia") . ".csv"; // filenme with date appended
$fp = fopen($filename, "w"); // open file
$row = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . $name; // write first value without a comma
$comma = ","; // add comma in front of each following value
}
$seperator .= "\n";
echo "Database has been exported to $filename";
fputs($fp, $seperator);
mysql_data_seek($query, 0); // use previous query leaving out first row
while($row = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . $value; // write first value without a comma
$comma = ","; // add comma in front of each following value
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
}
else
echo "There are no records in the database to export.";
mysql_close();
}
Following is PHP script which I am using.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employees";
$fp = fopen('php://output', 'w');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$table_name.'.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$result = mysql_query("SELECT * FROM $table_name");
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);
}
if ($fp && $result) {
fputcsv($fp, $headers);
while ($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
}
exit;
?>

Categories