I want to export my db data to CSV or asking user "Open with his local supporting program".
Exporting to csv I could understand using this code:
<?php
header("Content-type: text/csv; charset=UTF-8");
header('Content-Disposition: attachment; filename=Export.csv');
//connection
$con = mysql_connect('localhost', 'root', '');
if(!$con){
echo "Error connection";
}
//select db
$select_db = mysql_select_db('country', $con);
if(!$select_db){
echo "Error to select database";
}
mysql_set_charset("utf8", $con);
//Mysql query to get records from datanbase
$user_query = mysql_query('SELECT * FROM countries');
//While loop to fetch the records
$contents = "ccode,country\n";
while($row = mysql_fetch_array($user_query))
{
$contents.=$row['ccode'].",";
$contents.=$row['country']."\n";
}
$contents_final = chr(255).chr(254).mb_convert_encoding($contents, "UTF-16LE","UTF-8");
print $contents_final;
?>
How 2nd part could be managed? Showing option to open with local installed program?
Above code is correct?
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="your_file_name.csv"');
header('Content-Transfer-Encoding: binary');
This will cause the browser to display the dialog box to Save / Open the file.
You should also consider a) switching to mysqli_ or PDO and b) using PHP's built-in csv functions, e.g.
ob_start();
$f = fopen('php://output', 'w');
// $results comes from mysqli_ functions
foreach ( $results as $k => $v ) {
fputcsv($f, $v);
}
$output = ob_get_contents();
ob_end_clean();
echo $output;
Related
I'm having a hard time making my CSV export function work.
I've found around plenty of examples using mysqli_* functions, but I'm actually using PDOs so I had to adapt some questions/answers to my needs.
From what I can see, I'm properly parsing and writing data to the *.csv file, but at the end I don't simply get any "Download" modal from the browser.
Again, looking around, I've understood I may have some kind of problem with my headers, so I'm asking for your help.
This is my PHP function snippet:
function downloadAsCSV($dsn, $dbUser, $dbPsw, $options) {
// New PDO connection.
$pdo = pdoConnect($dsn, $dbUser, $dbPsw, $options);
$query = ... // Not going to write it down.
// Let's query the database, ...
$stmt = $pdo->prepare($query);
// Setting up the query variables here...
[...]
// Executing the statement...
$stmt->execute();
// Headers.
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename='export.csv'");
header("Pragma: no-cache");
header("Expires: 0");
// Let's open tbe "*.csv" file where we'll save the results.
$fp = fopen("php://output", "w");
if ($fp) {
$first_row = $stmt->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
fputcsv($fp, array_values($first_row));
fputcsv($fp, $headers);
// ... fetch the results...
$workpiecesArray = $stmt->fetchAll();
// ... and, finally, export them.
foreach ($workpiecesArray as $workpiece) {
fputcsv($fp, array_values($workpiece));
}
}
fclose($fp);
// Closing the connection.
$stmt = null;
$pdo = null;
}
function mysqli_field_name($result, $field_offset) {
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}
I've taken inspiration to write the table column titles from this answer.
What you need to do is to print the file, which you're not doing right now.
See this example using readfile:
http://php.net/manual/en/function.header.php#example-5554
Simply put:
1.Replace
$fp = fopen("php://output", "w");
with
$tmpfname = tempnam("/", "");
$fp = fopen($tmpfname, "w");
2.Replace
fclose($fp);
with
fclose($fp);
readfile($tmpfname);
unlink($tmpfname);
and this will work
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="export.csv"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('export.csv'));
readfile($csvFile);
exit;
`put this after` fclose($fp);
I'm going to modify the below php script such that it downloads the database as a .pdf file rather than in a .csv format. How should I do that? Currently when this script is called, the database will be downloaded as a .csv file. The database is defined in directadmin.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'db.php';
define("tableStuff", "stuff");
define("tableUser", "user");
define("ERR", '{"status":1}');
define("INVALID", '{"status":2}');
define("rowUserId", "user_id");
define("rowRegDate", "reg_date");
define("rowStuffName", "stuff_name");
define("rowPurchaseDate", "purchase_date");
define("rowStuffCount", "stuff_count");
define("rowStuffDescription", "stuff_description");
define("rowPicUrl", "pic_url");
define("rowUserName", "user_name");
//**********************************************************************
$mysqli = mysqli_connect(DBIP, DBUN, DBPW, DBNAME);
if ($mysqli->connect_errno) {
echo ERR;
die;
}
mysqli_set_charset($mysqli, "utf8");
$result = $mysqli->query("SELECT ".rowStuffName.",".rowStuffCount.",".rowStuffDescription.",".rowPurchaseDate.",".tableStuff.".".rowRegDate.",".rowUserName." FROM " . tableStuff .",".tableUser.
" WHERE " . tableStuff.".".rowUserId . " = " . tableUser.".".rowUserId);
if ($result->num_rows > 0) {
$array = array();
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$array[] = $row;
}
header('Content-Encoding: UTF-8');
header('Content-Type: application/csv; charset=utf-8' );
header(sprintf( 'Content-Disposition: attachment; filename=stuff.csv', date( 'dmY-His' ) ) );
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//echo pack("CCC",0xef,0xbb,0xbf);
$title = array("نام کالا","تعداد (مقدار)","توضیحات","زمان ثبت","نام فرد ثبت کننده");
$out = fopen("php://output", 'w');
//fputs($out,"\xEF\xBB\xBF");
fputcsv($out, $title,"\t");
foreach ($array as $data)
{
fputcsv($out, $data,"\t");
}
fclose($out);
} else {
echo INVALID;
}
mysqli_close($mysqli);
I am late,but i am using FPDF to generate all PDF files,It includes a built in example of making PDF with tables from CSV file,I just changed the source of CSV file.It is super easy.
I am trying to download the files from database. but it shows "failed to load" message.Uploading is working fine. i can upload pdf, jpg, dox file. but unable to open when i download.IF there are three href links in my file. first is for "upload" second is for "delete". every link download the file from image even other links are for other work but every file calls the downld.php file
<?php echo $name;?>
downld.php
<?php
if (isset($_GET['id']))
{
$project_id = $_GET['id'];
$myConnection= mysqli_connect("localhost","root","", "extra") or die ("could
not connect to mysql");
mysqli_set_charset($myConnection,'utf-8');
global $wpdb;
$sql = "SELECT name, type, size, content " .
"FROM wp_postprojectwin WHERE project_id = $project_id";
$result = mysqli_query($myConnection,$sql) or die('Error, query failed');
list($name, $type, $size, $content) = mysqli_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Description: PHP Generated Data");
header("Content-Transfer-Encoding: binary");
mysqli_close($connection);
ob_clean();
flush();
echo $content;
exit;
}
else{
echo "sorry";
}
?>
Here is the code I am using to try and retrieve an image from a database:
<?php
if($id)
{
//please change the server name username and password according to your mysql server setting
$mysql_server="localhost";
$mysql_username="myuser";
$mysql_password="mypass";
$mysql_database="mydb";
//connect to database using above settings
#MYSQL_CONNECT("localhost",$mysql_username,$mysql_password);
#mysql_select_db("mydb");
//select the picture using the id
$query = "select bin_data,filetype from todo where id=$id";
//execute the query
$result = #MYSQL_QUERY($query);
//get the picture data which will be binary
$data = #MYSQL_RESULT($result,0,"bin_data");
//get the picture type. It will change according to file extension it may be either gif or jpg
$type = #MYSQL_RESULT($result,0,"filetype");
//send the header of the picture we are going to send
Header( "Content-type: $type");
//send the binary data
echo $data;
};
?>
Instead of displaying the requested image, it displays this icon: (not sure what you call it)... http://i.imgur.com/bo6Jg.png
Here are all the columns in my table: http://i.imgur.com/PuWvl.png
I'm pretty positive I'm doing everything right...not sure what's going on. Help anyone? Thanks in advance!
IMO only constants should be uppercase (tho I gladly did not know they could be upper),
Anyway Try this:
<?php
$file_not_found = '../not_found_image.jpg';
//Get the id param from GET else null
$id = (isset($_GET['id']) && is_numeric($_GET['id']))?$_GET['id']:null;
if($id != null) {
$mysql_server="localhost";
$mysql_username="myuser";
$mysql_password="mypass";
$mysql_database="mydb";
//Connect to database using above settings
mysql_connect($mysql_server,$mysql_username,$mysql_password) or die(mysql_error());
mysql_select_db($mysql_database) or die(mysql_error());
//Select the picture using the id
$query = "SELECT `bin_data`, `filetype` FROM todo WHERE id=".(int)mysql_real_escape_string($id)." LIMIT 1";
//Execute the query
$result = mysql_query($query);
//Found
if(mysql_num_rows($result)==1){
//Get the picture data which will be binary
$data = mysql_result($result,0,"bin_data");
//Get the picture type. It will change according to file extension it may be either gif or jpg
$type = mysql_result($result,0,"filetype");
//Send the header of the picture we are going to send + cache
header('Cache-Control: private, max-age='.(60*60*24*365));
header('Expires: '.gmdate(DATE_RFC1123,time()+60*60*24*365));
header("Pragma: private");
header('Content-Type: '.$type);
header('Content-Length: ' . strlen($data));
//Send the binary data
echo $data;
}else{
//Not found
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($file_not_found));
readfile($file_not_found);
}
}else{
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($file_not_found));
readfile($file_not_found);
}
?>
Try this..
header("Content-type: image/gif");
$expires = 60*60*24*14;
header("Pragma: public");
header("Cache-Control: maxage=".$expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
error_reporting(0);
require_once "class/dbconn.php";
$id=$_GET['id'];
$sql="select thumbimage from image where img_id=$id";
$rs=mysql_query($sql) or die (mysql_error());
$row =mysql_fetch_array($rs,MYSQL_BOTH);
$data = $row[0];
print $data;
I am recording the time at which the user downloaded a specific file using the following code. However, in this code, initially the download time is coming but later it's disconnecting the data base connection between client and server. If I remove the 'exit' (as shown), everything is coming fine but the downloaded file can be corrupted or damaged.
Can anyone check this code and explain what is wrong with it? I think the problem is with the exit, but what can I use instead of exit?
<?php
$f_name = $_POST["fn"];
$file = "../mt/sites/default/files/ourfiles/$f_name";
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
//ob_clean();
// flush();
readfile($file);
// exit;
}
$con = mysql_connect("localhost","mt","mt");
if (!$con) {
die('Could not connect: ' . mysql_error());
} else {
echo "Connected";
}
// Create table
mysql_select_db("mt", $con);
mysql_query("INSERT INTO down_time (FileName,DateTime)
VALUES ('".$f_name."',NOW())");
mysql_close($con);
?>
If that happens on large files and/or slow connections, try to tweak max_execution_time in php.ini or from script using ini_set function.
well if you include the exit, your code just doesn't come to the point where it should insert the filename into db.
if you don't include the exit, you send the file contents and append "Connected" to it so the file has to be corrupted.
maybe you can try ob_start and ob_end_clean around your db stuff: http://php.net/manual/en/function.ob-start.php
this prevents anything from being sent to the output, so you don't have to use exit but nothing gets sent to the output after your file so it doesn't get corrupted
something like:
readfile($file);
}
ob_start();
$con = mysql_connect("localhost","mt","mt");
//all the DB stuff
mysql_close($con);
ob_end_clean();
?>
you can include exit after the ob_end_clean() just to be sure but this should work just fine.
Try:
<?php
$f_name = $_POST["fn"];
$file = "../mt/sites/default/files/ourfiles/$f_name";
if (!file_exists($file)) { die('File not found'); }
if (!$con = mysql_connect("localhost","mt","mt")) { die(mysql_error()); }
if (!mysql_select_db("mt")) { die(mysql_error()); }
$q = "INSERT INTO `down_time` (`FileName`, `DateTime`) VALUES ('"
. mysql_real_escape_string($f_name) . "',NOW())";
if (!mysql_query($q)) { die(mysql_error()); }
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($file);