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
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.
First let me introduce myself:
Im 33. 'Living in the Netherlands and i'm a newbe if it comes to php :)
I have a csv file on my vps httpdocs\data\1day.csv . In this file there are two columns: datetime and value. The file looks like this:
"datetime","value",
"2016-01-02 10:50:01","1060.9",
"2016-01-02 10:45:01","1060.6",
I want to make a simple calculation to the file 1day.csv and save it to another csv file. Let's say the caluclation will be value * 5:
"datetime","value","value2",
"2016-01-02 10:50:01","1060.9","5304.5",
"2016-01-02 10:45:01","1060.9","5304.5",
The calculation needs to be done over the whole "value" column.
I want to do this with php and let a cronjob execute this script every x minutes.
Can anybody help me in the right direction?
I would maybe do it more simple. If you didn't know how many columns you could do the extra loops to get column names, but it does not look necessary.
$output = "datetime, value1, value2\n"; // Column names
while ($row = mysql_fetch_array($sql)) {
$output .='"' . $row[0] . '" ,';
$output .='"' . $row[1] . '" ,';
$output .='"' . ($row[1] * 5) . '"';
$output .="\n";
}
#riggsfolly
Ok. This is what i got so far:
// Database Connection
$host="localhost";
$uname="xxxxx";
$pass="xxxxx";
$database = "xxxxx";
$connection=mysql_connect($host,$uname,$pass);
echo mysql_error();
//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or
die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");
// Fetch Record from Database
$output = "";
$table = "quotes"; // Enter Your Table Name
$sql = mysql_query("select datetime, value from $table where type = '5' order by datetime desc limit 333");
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Save the file
$directory = "/var/www/vhosts/domain.nl/httpdocs/data/";
$filename = "1day.csv";
$fd = fopen ("$directory" . $filename, "w");
fputs($fd, $output);
fclose($fd);
exit;
The part where i get stuck is to add the extra column with the calculated value.
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;
?>
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.