Set database column alias before exporting csv - php

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.

Related

Php mysql Get&Post query to excel

I have a page that posts to index page like
index.php?coursecode=COURSECODEHERE
My non-variable query works well. Gives me all table as excel file.
I need to use this query with variables.
<?php
require_once('dbconnect.php');
$setCounter = 0;
$setExcelName = "download_excal_file";
$setSql = "SELECT * FROM courses WHERE coursecode POSTED VARIABLE COURSECODE HERE";
$setRec = mysql_query($setSql);
$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++) {
$setMainHeader .= mysql_field_name($setRec, $i)."\t";
}
while($rec = mysql_fetch_row($setRec)) {
$rowLine = '';
foreach($rec as $value) {
if(!isset($value) || $value == "") {
$value = "\t";
} else {
//It escape all the special charactor, quotes from the data.
$value = strip_tags(str_replace('"', '""', $value));
$value = '"' . $value . '"' . "\t";
}
$rowLine .= $value;
}
$setData .= trim($rowLine)."\n";
}
$setData = str_replace("\r", "", $setData);
if ($setData == "") {
$setData = "\n no matching records found\n";
}
$setCounter = mysql_num_fields($setRec);
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";
?>
How can i do that ?
1.- mysql_ is deprecated, switch to PDO or mysqli ASAP
2.- Always sanitize the input, you never know who may call your link and insert stuff (or delete stuff) from your database.
Said that, you can do something like:
$setSql = "SELECT * FROM courses WHERE
coursecode LIKE '".sanitizeThisShit($_GET["coursecode"])."'";

A blank line is inserted at the beginning when Creating CSV using PHP MySQL

I am trying to get the contents of the MySQL table to a CSV file. Everything works fine except that a blank row is being inserted before the heading label that I pass through Array.
<?php
error_reporting(0);
ob_start();
session_start();
include 'auto_logout.php';
//echo $_SESSION['fullname'];
if ((!isset($_SESSION['ufullname'])) && (!isset($_SESSION['fullname']))) {
/* Redirect browser */
header("Location: index.php");
/* Make sure that code below does not get executed when we redirect. */
exit();
}
$output = "";
require_once('config/config.php');
require_once("includes/ftp_settings.php");
$table = "Download CSV"; // Enter Your Table Name
if (is_array($new_exist) && (is_array($ftp1))) {
$ressd_new = 'select filename from files where uploaded_by IN ("' . implode('","', $new_exist) . '")';
$resd_new = mysql_query($ressd_new);
while ($kkk_new = mysql_fetch_array($resd_new)) {
$gotit_new = $kkk_new[0];
}
$resultka_new = $ftp1;
$sql = 'SELECT slno, filename, uploaded_by, dateadded, timeadded, size FROM files where uploaded_by IN ("' . implode('","', $new_exist) . '") and filename IN ("' . implode('","', $resultka_new) . '") and size != "0"';
} else {
$sql = "SELECT slno, filename, uploaded_by, dateadded, timeadded, size FROM files where ftp_file = '$ftp_server' and ftp_u_file = '$ftp_user_name' and ftp_p_file = '$ftp_user_pass' and size != '0'";
}
$sql = mysql_query($sql);
$columns_total = mysql_num_fields($sql);
// Get The Field Name
$heading1 = array(
"Sl. No.",
"File Name",
"Uploaded By",
"Date Added",
"Time Added",
"Size"
);
$inc = 0;
for ($i = 0; $i < $columns_total; $i++) {
$heading = $heading1[$inc];
$output .= '"' . $heading . '",';
$inc = $inc + 1;
}
$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";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
echo $output;
exit;
?>
Not really sure where is the blank line coming from.
Including files will often add unwanted whitespaces if not cared properly.
Suppressing errors will make the things worse in every case.
The reason you need ob_start() is because the script between ob_start() and "echo $output;" is printing some content (your empty line probably). And therfore you can't set headers. I'll bet it's in your included files (auto_logout, config, ftp_settings).
Allow errors, remove ob_start, solve all warnings, profit.
And btw: Do not use mysql extension, use mysqli instead.

Make calculations in csv with php

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.

Php to csv export with comma delimiter in separate cells

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;
?>

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, ';', '"');

Categories