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 ,.
Related
Here is my code who works very well.When i call this file from browser it downloads my file in CSV format.
<?php
/* vars for export */
// database record to be exported
$db_record = 'people';
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'exported.csv';
// database variables
$hostname = "localhost";
$user = "root";
$password = "";
$database = "db1";
// Database connecten voor alle services
mysql_connect($hostname, $user, $password)
or die('Could not connect: ' . mysql_error());
mysql_select_db($database)
or die ('Could not select database ' . mysql_error());
// create empty variable to be filled with export data
$csv_export = '';
// query to get data from database
$query = mysql_query("SELECT * FROM ".$db_record." ".$where);
$field = mysql_num_fields($query);
// create line with field names
for($i = 0; $i < $field; $i++) {
$csv_export.= mysql_field_name($query,$i).';';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
}
$csv_export.= '
';
}
// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
?>
Assume that the files generated is like this:
"name", "age", "country"
"Gulizer", "21", "Kurdistan"
"Pierre", "20", "France"
What i want is retreive age again and put it at the and of each lines with some text like
"name", "age", "country", "text_added"
"Gulizer", "21", "Kurdistan", "The age of Gulizer is 21"
Is it possible?
I found the solution by myself and share with you
I added
echo "text_added;";
just after
for($i = 0; $i < $field; $i++) {$csv_export.= mysql_field_name($query,$i).';';}
$csv_export.= '\n';
and changed
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
}
$csv_export.= '
';
}
to
for($i = 0; $i < $field; $i++) { $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";'; }
$csv_export.= '
'.$row['age'].'years old";';
}
and finally i got this result:
text_added;name;age;country
"21 years old"; "Gulizer"; "21"; "Kurdistan"
"20 years old"; "Pierre"; "20"; "France";
exactly what i want.
There are 2 blank rows at the top of csv when script is run...Have no idea why. This code works in another application I've made. I'm using the same code and same database??
Does the location in directory make a difference?
<?php
mysql_connect("", "", "")
or die(mysql_error());
mysql_select_db("dbname")
or die(mysql_error());
$database = "mydb";
//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 = "";
// Store Matching
$sql = mysql_query("SELECT audiolist.`Store Number`, audiolist.Address, audiolist.City, audiolist.State, audiolist.`Zip Code`, audiolist.`Install Date`
FROM audiolist INNER JOIN filteredlist ON audiolist.`Store Number`=filteredlist.`Store Number`");
$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 = "myfilename" . date("Y-m-d") . ".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
Not exactly sure why it matters...but apparently if there are any lines before the initial <?php tag, those lines show up as plank rows when the csv is generated. There were two lines before mine and therefore 2 blank rows...It works now!
After this line of your code:
header('Content-Disposition: attachment; filename='.$filename);
Add this code:
ob_clean(); // discard any data in the output buffer (if possible)
flush();
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 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().
How Can I download .sql file using php code or codeigniter code!
$this->dbutil->backup()
Permits you to backup your full database or individual tables. The backup data can be compressed in either Zip or Gzip format.
Note: This features is only available for MySQL databases.
Note: Due to the limited execution time and memory available to PHP, backing up very large databases may not be possible. If your database is very large you might need to backup directly from your SQL server via the command line, or have your server admin do it for you if you do not have root privileges.
Usage Example
// Load the DB utility class
$this->load->dbutil();
// Backup your entire database and assign it to a variable
$backup =& $this->dbutil->backup();
// Load the file helper and write the file to your server
$this->load->helper('file');
write_file('/path/to/mybackup.sql', $backup);
// Load the download helper and send the file to your desktop
$this->load->helper('download');
force_download('mybackup.sql', $backup);
follw the link
Here is complete PHP code to download the database backup
<?php
// Database configuration
$host = "localhost";
$username = "db-username";
$password = "db-password";
$database_name = "db-name";
// Get connection object and set the charset
$conn = mysqli_connect($host, $username, $password, $database_name);
$conn->set_charset("utf8");
// Get All Table Names From the Database
$tables = array();
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$sqlScript = "";
foreach ($tables as $table) {
// Prepare SQLscript for creating table structure
$query = "SHOW CREATE TABLE $table";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$sqlScript .= "\n\n" . $row[1] . ";\n\n";
$query = "SELECT * FROM $table";
$result = mysqli_query($conn, $query);
$columnCount = mysqli_num_fields($result);
// Prepare SQLscript for dumping data for each table
for ($i = 0; $i < $columnCount; $i ++) {
while ($row = mysqli_fetch_row($result)) {
$sqlScript .= "INSERT INTO $table VALUES(";
for ($j = 0; $j < $columnCount; $j ++) {
$row[$j] = $row[$j];
if (isset($row[$j])) {
$sqlScript .= '"' . $row[$j] . '"';
} else {
$sqlScript .= '""';
}
if ($j < ($columnCount - 1)) {
$sqlScript .= ',';
}
}
$sqlScript .= ");\n";
}
}
$sqlScript .= "\n";
}
if(!empty($sqlScript))
{
// Save the SQL script to a backup file
$backup_file_name = $database_name . '_backup_' . time() . '.sql';
$fileHandler = fopen($backup_file_name, 'w+');
$number_of_lines = fwrite($fileHandler, $sqlScript);
fclose($fileHandler);
// Download the SQL backup file to the browser
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($backup_file_name));
ob_clean();
flush();
readfile($backup_file_name);
exec('rm ' . $backup_file_name);
}
?>
Reference: https://phppot.com/php/how-to-backup-mysql-database-using-php/