I am trying to download an excel file from MySql database records but i am not getting where i am wrong. Here is my code.
$sql_ft1 = "SELECT `Id`,`fname`,`lname` FROM users";
$rs_ft1 = mysql_query($sql_ft1) or die(mysql_error());
$total1=mysql_num_rows($rs_ft1);
$output.=' <table border="1">
<tr>
<th>Sr NO.</th>
<th width="120">User Name</th>
<th>Password</th>
</tr>
';` while($data = mysql_fetch_assoc($rs_ft1))
{`$output.= '
<tr>
<td>'.$data["Id"].'</td>
<td>'.$data["fname"].'</td>
<td>'.$data["lname"].'</td>
</tr>
'; }
$output.='</table>';
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=User_Detail_Reoprt.xls");
echo $output;
i made a new code with ur code as its giving php errors. I changed some " to ' and also in content header i changes filename " but it did not worked
$strtable.='<table border="1"><tr><th>Sr NO.</th><th width="120">User Name</th><th>Password</th>';
$sql_ft1 = "SELECT `Id`,`fname`,`lname` FROM users";
$rs_ft1 = mysql_query($sql_ft1) or die(mysql_error());
$total1=mysql_num_rows($rs_ft1);` while($data = mysql_fetch_assoc($rs_ft1)){$strtable.='<tr>
<td>'.$data["Id"].'</td>
<td>'.$data["fname"].'</td>
<td>'.$data["lname"].'</td>';
}
$strtable.='</tr>';
$strtable.='</table>';
echo $strtable;
$data = ob_get_contents();`
ob_end_clean();
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=User_Detail_Reoprt.xls");`header("Pragma: no-cache");
header("Expires: 0");
print $data;
echo $filename;
Try this,
$strtable.="<table border="1"><tr><th>Sr NO.</th><th width="120">User Name</th><th>Password</th>";
$sql_ft1 = "SELECT `Id`,`fname`,`lname` FROM users";
$rs_ft1 = mysql_query($sql_ft1) or die(mysql_error());
$total1=mysql_num_rows($rs_ft1);
$strtable.="<tr>
<td>$data["Id"]</td>
<td>$data["fname"]</td>
<td>$data["lname"]</td>";
$strtable.="</tr>";
$strtable.="</table>";
echo $strtable;
$data = ob_get_contents();
ob_end_clean();
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename="User_Detail_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$data";
change your variable and check result hope it work
$this->excel->setActiveSheetIndex(0);
$filename = "myfile.xls";
$header = array("coulmn1","column2");
$list = array ($header);
foreach($query_result as $result_view){
$list[] = array($result_view->value1,$result_view->value2,
}
$this->excel->getActiveSheet()->fromArray($list);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save($filename);
echo $filename;
Related
when download image image is can't open .it just 4kb file.please help. image type is in blob.its downloading file.but can't visible.
<?php
if(isset($_GET['task_id'])){
$id = $_GET['task_id'];
$sql = "SELECT * FROM workload WHERE TID = $id ";
$info = $obj_admin->manage_all_info($sql);
$num_row = $info->rowCount();
if($num_row>0){
$i=0;
}
while( $row = $info->fetch(PDO::FETCH_ASSOC) ){
$image = 'images_uploaded/'. $row['imageA'];
header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="table_with_image_image'.$id.'.jpg"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($image));
echo $image;
exit();
}
}
?>
I am using directory path that i save in database. how can i download from path. my code is.
if(isset($_POST['download'])) {
$id = $_GET['id'];
$query = "SELECT url_video FROM website WHERE id = '$id'";
$result = mysql_query($query); $rowss = mysql_fetch_assoc($query);
$name2 = $rowss['url_video'];
header("Accept-Ranges: bytes");
header("Keep-Alive: timeout=15, max=100");
header('Content-Disposition: attachment; filename='.$name2);
header("Content-type: video/mp4");
//header("Content-Transfer-Encoding: binary");
header( "Content-Description: File Transfer");
exit;
}
?>
You need to output/echo the content of the file after you set the download headers.
Also the following
header('Content-Disposition: attachment; filename='.$name2);
should be
header('Content-Disposition: attachment; filename='.$file_name_not_full_path);
or
header('Content-Disposition: attachment; filename=downloadedvideo.mpg');
Full code (i assume you have a column named video_path that stores the path to the file on the server:
if(isset($_POST['download'])) {
$id = $_GET['id'];
query = "SELECT url_video, video_path FROM website WHERE id = '$id'";
$result = mysql_query($query);
$rowss = mysql_fetch_assoc($query);
header("Accept-Ranges: bytes");
header("Keep-Alive: timeout=15, max=100");
header('Content-Disposition: attachment; filename='.$rowss['url_video']);
header("Content-type: video/mp4");
header("Content-Transfer-Encoding: binary");
header( "Content-Description: File Transfer");
readfile($rowss['video_path']);
}
New code version after last comments:
if(isset($_POST['download'])) {
$id = $_GET['id'];
query = "SELECT url_video FROM website WHERE id = '$id'";
$result = mysql_query($query);
$rowss = mysql_fetch_assoc($query);
header("Location: ".$rowss['url_video']);
exit();
}
I have the following PHP code using headers to download a file from the server:
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
This code works fine, however I have it in a file with the HTML form and it is ran using an if isset all of the HTML code is placed in the file, as well as anything I echo out in PHP; and the data I actually want in the file is there at the end.
I can't figure out what in the headers is causing it to write everything that is on screen to the file when downloaded. The file on he server isn't changed and is how it should be.
Thanks for any help.
Heres all the code...
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post"><br>
Order Number: <input type="number" name="orderNo" size="10"/>
<input type="submit" name="Download" value="Download" />
</form>
</body>
</html>
<?php
if(isset($_POST['Download'])){download();}
function download()
{
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('amazondb', $conn);
$result = mysql_query("SELECT ID, PurchaseDate, BuyerName, ShipCity, ShipState, ShipPostalCode, ShipCountry,
ShipAddress1, ShipAddress2, ShipAddress3 FROM imported_orders");
$orderNo = $_POST['orderNo'];
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($orderNo>0&&$orderNo<=count($row))
{
$file = fopen('Order.txt', 'w');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if($row['ID']==($orderNo))
{
echo "Hello";
fwrite($file, $row['BuyerName'].PHP_EOL .$row['ShipAddress1'].PHP_EOL .$row['ShipAddress2'].PHP_EOL .$row['ShipAddress3'].PHP_EOL .$row['ShipCity'].PHP_EOL .$row['ShipState'].PHP_EOL .$row['ShipPostalCode'].PHP_EOL .$row['ShipCountry'].PHP_EOL);
}
}
fclose($file);
$file = 'Order.txt';
header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
else{echo "Please enter a valid Order Number"; echo $orderNo;}
}
move this code at very begin of file, so you will have:
<?php
if (your condition to output file) {
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
die();
}
the rest of your file....
another solution, at the very top of file add:
<?php
ob_start() or die('Cannot start output buffering');
... your page
and just before the first header add:
$file = 'Order.txt';
ob_end_clean();
header("Cache-Control: public");
...
readfile($file);
die();
I'm trying to download a list of email addresses from a database in WordPress to .CSV.
Anybody point me in the right direction:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$results = $wpdb->get_results( "SELECT * FROM table");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data = json_encode($row);
}
outputCSV($data);
function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
}
This will do the trick:
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="filename.csv"');
header("Pragma: no-cache");
header("Expires: 0");
echo '"Header 1","Header 2","Header 3"'."\n";
$results = $wpdb->get_results("SELECT * FROM `wp_newsletter_signup`");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
echo '"' . $row['column1'] . '","' . $row['column2'] . '","' . $row['column3'] . '"' . "\n";
}
die();
Note my content type of application/vnd.ms-excel I use this as personal preference due to higher support in older windows machines, but you can continue to use text/csv - A list of mime types can be found here http://filext.com/file-extension/CSV
Change
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data = json_encode($row);
}
to
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data[] = $row;
}
i have a table which shows some mysql data, every entry has a checkbox to select individual entries, now i want to be able to export those selected entries into a xml or txt file, i tried this:
<?php
if ($_POST['exporttxt']) {
for ($i = 0; $i < count($_POST['checkbox']); $i++) {
$export_id = $checkbox[$i];
$sql = "SELECT * FROM table WHERE id='$export_id'";
$result = mysql_query($sql);
}
$output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n";
if ($result->num_rows > 0) {
while ($myrow = $result->fetch_assoc())
{
$output .= "\t<row>\n";
foreach ($myrow as $_name => $_value)
{
$output .= "\t\t<$_name>$_value</$_name>\n";
}
$output .= "\t</row>\n";
}
}
$output .= "</root>";
}
header('content-type: text/xml');
header('content-disposition: attachment; filename=data_export.xml');
echo $output;
exit;
?>
But that didn't work at all, any hints ?
I've changed the code a bit, i am now using this
<?php
if ($_POST['exporttxt']) {
for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];
$text = mysql_query("SELECT code FROM ticket WHERE id='$export_id'");
$text = mysql_fetch_assoc($text);
$text = $text["code"];
ob_end_flush();
header("Content-type: text/plain");
header("Content-disposition: attachment;filename=\"filename.txt\"");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo($text);
}
}
?>
I now get proper output on my screen, but it won't offer me to download the file ?
Your original code was querying each of the checkboxed IDs individually (a long and laborious way to handle it) and was trying to dump the results individually per row (not going to work well for you).
Try this. (NOTE: Untested, but should give you a good starting point to develop.)
if( $_POST['exporttxt'] ){
if( count( $_POST['checkbox'] )>0 ){
// If the checkbox values are meant to all be integers, you might want to perform some validation/sanitisation/filtering here
// Up to you to do that
// Collapse the IDs from the checkboxes into a comma-delimited string
$export_ids = implode( ',' , $_POST['checkbox'] );
// Template the SQL Query
$sqlTpl = 'SELECT code FROM ticket WHERE id IN ( %s )';
// Compile the SQL Query String
$sqlStr = sprintf( $sqlTpl , $export_ids );
// Execute the SQL Query
if( !( $sqlRes = mysql_query( $sqlStr ) ) ){
// SQL Error - Log it, Handle it
}elseif( mysql_num_rows( $sqlRes )==0) {
// No Rows Returned - Log it, Handle it
}else{
// We have results - process them
$text = array();
while( $r = mysql_fetch_assoc( $sqlRes ) ){
// Looping through the returned rows, adding them to the $text array
$text[] = $r['code'];
}
// Collapse the $text array down into a normal string, with one element per line
$output = implode( "\n" , $text );
// Output Handling from #narcisradu's answer
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary;\n");
header("Content-Disposition: attachment; filename=\"filename.txt\";\n");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo $output;
die; // Prevent any further output
}
}else{
// No Checkboxes Checked
echo 'You must select one or more checkboxes to export something, muppet.';
}
}
First of all:
for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];
$sql = "SELECT * FROM table WHERE id='$export_id'";
$result = mysql_query($sql);}
This piece of code will actually do a query for every element in _POST['checkbox'] array but then you are using the result of the last query and you are not parsing the result of every query.
Please make sure the generated XML is well-formed and you actually have some data, by displaying directly into the browser.
After that you may try to force download:
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary;\n");
header("Content-Disposition: attachment; filename=\"".urlencode(basename($file_name))."\";\n");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
ob_end_flush();