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.
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 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.
I created a code in php that performs a search on twitter and saves the result (100 tweets ) in a database . In this code , I also have the option to select all database tweets and exports them to a csv file.
However, if the tweet has a line break he'll be that way in csv :
What do I do to save this tweet on one line of the csv ( delete line break )
This is my code that exports tweets to csv :
// Database Connection
$host="xxxxxx";
$uname="xxxxx";
$pass="xxxxxx";
$database = "xxxxxx";
$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 = "tabela_tweets_novo"; // Enter Your Table Name
$sql = mysql_query("select tweet from $table");
$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++) {
$acentua = utf8_decode($row["$i"]);
$output .='"'.$acentua.'",';
}
$output .="\n";
}
// Download the file
$filename = "UUXPost.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
Insert the 3 Line in your Code and change the replace string to what you want
$acentua = utf8_decode($row["$i"]); <- your code
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
$acentua = str_replace($order, $replace, $acentua);
$output .='"'.$acentua.'",'; <- your code
You should use PHP's built-in csv methods that'll handle escaping for you (you'll have to escape fields with linebreaks).
Sadly I'm on my mobile right now so it's quite a pita to add the urls. I'll do that later (or some editor).
Search the PHP manual for fputcsv().
I Try this solution to export from my database to CSV and it work but all Data are exported in one colones. I would like that compose me in The CSV like in the table data base. What is the problem in this code ?
<?php
// Database Connection
$host="localhost";
$uname="root";
$pass="";
$database = "a2zwebhelp";
$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 = ""; // Enter Your Table Name
$sql = mysql_query("select * from $table");
$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";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
?>
If you use "\n" as a line separator and open that file in i.e. notepad.exe, this will not be properly recognized as "carriage return linefeed" and the entire file seems to be just "one big line" - but actually it isn't!
You may terminate lines with "\r\n" to prevent this effect.
In order to have this automatically recognized by i.e. Excel, use ; as field separator instead of ,.
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.