I have found this code here, and I should use it for my website. But although everything seems fine, somehow delimiter is not working. As you can see, I put comma (,) to be a delimiter and when in mysql there is (|) I put it to be changed to comma again to be separate in cells.
But, I got a result that everything is in first cells. There are commas, but it is not split. So, if I click in excel data > delimiter and split by commas - then it is ok.
How to fix this? I am new, so is there an easy specific change here?
$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;
?>
Related
I have an php script, which i want to use to automatically export data from a certain mysql table, to a CSV file in a directory. The script is working fine and the files are saved in the right directory, but u want, that every order, exports to a separate CSV file.
Like:
12-09-2016-05-21_csvexport_1.CSV < data from order 1
12-09-2016-05-21_csvexport_2.CSV < data from order 2
And so on..
I want to run the script automatically with a cronjob. The orders to be exported as a separate csv file, can be selected with a date range. Like only create csv files from the last 2 days. It doesn't matter if the CSV files are going to overwrite.
The order table looks like this:
id_order date customer
1 01-01-2016 1223
2 01-02-2016 1224
3 01-03-2016 1225
4 01-04-2016 1226
5 01-05-2016 1227
And the php script looks like this:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'database';
$table = 'columns';
$file = 'csvexport';
$dir = 'csv';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
function escape_csv_value($value) {
$value = str_replace('"', '""', $value);
if ( preg_match( '/\\r|\\n|,|"/', $value ) ) {
return '"' . str_replace( '"', '""', $value ) . '"';
} else {
return $value;
}
}
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$values = mysql_query("SELECT id_order, date, customer FROM orders");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= escape_csv_value($rowr[$j]).';';
}
$csv_output .= "\n";
}
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: attachment; filename=".$filename.".csv");
$filename = date("d-m-Y-i-s_", time()) . $file.".csv";
print $csv_output;
file_put_contents($dir ."/".$filename, $csv_output);
}
?>
I hope someone can help me. Thanks in advance.
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, ';', '"');
Hey guys I am trying to export a csv in my script and it works perfectly. Now what I need to do, is rename the columns to clean names and proper names before fully exporting the csv.
Here is a picture of the database table: http://i.imgur.com/aQrOZLk.png
Here is the code:
include_once "config.php";
$table = 'patients'; // table you want to export
$file = 'export'; // csv name.
$result = mysql_query("SHOW COLUMNS FROM " . $table . "");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'] . ",";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM " . $table . "");
while ($rowr = mysql_fetch_row($values)) {
for ($j = 0; $j < $i; $j++) {
$csv_output .= $rowr[$j] . ", ";
}
$csv_output .= "\n";
}
$filename = $file . "_" . date("d-m-Y_H-i", time());
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;
?>
As you can see it fetches the table names from this code:
$result = mysql_query("SHOW COLUMNS FROM " . $table . "");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'] . ",";
$i++;
}
}
Now what I am trying to do is allow it to rename the database tables from
pat_id to Patient ID
pat_fname to Patient First Name
pat_lname to Patient Last name
and so on. To make it looks neat and readable in the csv file.
How am I able to do that? I already tried a few codes like:
$query = 'SHOW COLUMNS pat_id AS "user_id", pat_fname AS "first name", pat_lname AS "last name" FROM ' . $table;
But it didnt work and gives off errors.
You want to use friendly column names in your select, not your show columns.
Try something like this instead of SELECT * :
$query = "SELECT pat_id AS 'user_id', pat_fname AS 'first name', pat_lname AS 'last name' FROM table";
Notice that MySQL expects your column names to be shown in single quotes, not double quotes.
To handle this stuff as column headers in csv ... try this.
$values = mysql_query($query);
$i = mysql_num_fields($values);
for ($j = 0; $j < $i; $j++) {
$csv_output .= mysql_field_name($j) . ", ";
}
$csv_output .= "\n";
while ($rowr = mysql_fetch_row($values)) {
for ($j = 0; $j < $i; $j++) {
$csv_output .= $rowr[$j] . ", ";
}
$csv_output .= "\n";
}
Since you are going to deal with many tables, create a multidimensional array and predefine the field names in it.
Like this,
$tables['table1'][1]="";
$tables['table1'][2]="";
$tables['table2'][1]="";
Then replace this block,
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'] . ",";
$i++;
}
}
with a block to fetch the field names of the table from your array.
This is the only way to do it.
I am attempting to add a function that will create a csv for download from a certain table in the db. I have got it partially working but cannot figure out how to exclude certain columns from the rows section of the csv. Here is my code so far,
$host = 'xxx';
$user = 'xxxx';
$pass = 'xxxx';
$db = 'xxxx';
$table = 'headers';
$file = 'export';
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$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." WHERE Field NOT IN ('invhead_id', 'note');");
$i = 0;
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values))
{
for ($j=0;$j<$i;$j++)
{
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
print $csv_output;
exit;
I have excluded the columns invhead_id and note from the $result output but also need to exlude them from the $values output as well however this is the bit I cannot get to work. Can anyone point me in the right direction?
Thanks
The easiest way is to select your columns by name instead of select *
There is no easier way, but you could also write a php function that compares your two arrays and discards the ones you don't want based on the first array and....you should just use my first idea.
SELECT field1, field2, field7 FROM table
Using PHP, I can convert MySQL data or static table data to csv, Excel, JSON, MySQL etc but is there a useful conversion script or tool that can convert table data into other formatted/styled formats such as PDF and/or JPG/PNG using the PHP GD Library or other?
I've used this before to turn a HTML table into a PDF. I generated the table from a MySQL query.
To export to Excel I use the following code:
<?php
/* Define our Database and Table Info */
$username="";
$password="";
$database="";
$table="";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$select = "SELECT * FROM $table";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . "\t";
}
while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("\r","",$data);
if ($data == "") {
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=mailinglist.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>
Now be careful with how you include this. It's using the Headers to send the file information to force a download, by doing this you can't have any white space anywhere before these headers are sent otherwise it may throw an error. I usually have this link open as a new window to prevent anything from happening... Again this is just a pretty basic script that can be expanded greatly. Hope this Helps!
<?php
/ Define our Database and Table Info /
$username="";
$password="";
$database="";
$table="";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$select = "SELECT * FROM $table";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . ",";
}
while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = ",";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . ",";
}
$line .= $value;
}
$data .= trim($line)."n";
}
$data = str_replace("r","",$data);
if ($data == "") {
$data = "n(0) Records Found!n";
}
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=mailinglist.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$headern$data";
?>