I've searched all the posts, but still couldn't get it to work. With button press I want to export "page preset" to be precise it's restaurant menu preset, it includes css files, mysql tables etc. I want to be able to import it to another 'menu'. First I'm trying to export mysql database. Should I use mysqldump or SELECT * INTO OUTFILE ?
I'm using this line:
exec("mysqldump --user=$dbusername --password=$dbpassword restaurantsdb meal --where=restaurant_id=$restId > tables/meal.sql");
restaurantsdb is database name and meal = table name. I also want rows WHERE 'restaurant_id' = {id}
I'm trying to understand how mysqldump works, should this line work for me?
Next I'm creating zipArchive file, adding some directories, I tried adding .txt file, that one works, but it doesn't seem to find meal.sql file.
$zip = new ZipArchive();
if ( $zip->open($zip_file, ZipArchive::CREATE) !== TRUE) {
exit("error");
}
$zip->addEmptyDir('TestFiles');
$zip->addEmptyDir('tables');
$fileToZip = __DIR__.'/hello.txt';
$zip->addFile($fileToZip, "TestFiles/text.txt");
$fileToZip = __DIR__.'/tables/meal.sql';
$zip->addFile($fileToZip, "tables/meal.sql");
$download_file = file_get_contents( $file_url );
$zip->addFromString(basename($file_url),$download_file);
$zip->close();
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($zip_file).'"');
header("Content-length: " . filesize($zip_file));
header("Pragma: no-cache");
header("Expires: 0");
ob_clean();
flush();
readfile($zip_file);
unlink($zip_file);
exit;
Also, is it better to export as .sql or .csv ? Later when importing, I need to be able to change id's of all rows to specified, just before importing to database. It's basically cloning same data, but different id's.
Related
i'm trying to export from mysql to excel using PHPExcel, i create a button to start exporting proses. It's loading but return with blank white page, i check every line from the code and didn't found any problem. Calling data from table is normal, check it with echo. so i think there is a problem with exporting process, here is the code
require_once 'PHPExcel/PHPExcel.php';
$excel=new PHPExcel();
$excel->getProperties()->setCreator('Flora Sitinjak')
->setLastModified('Flora Sitinjak')
->setTittle('Laporan Pendapatan')
->setSubject('Pendapatan')
->setDescription('Laporan Semua Pendapatan')
->setKeywords('Data Pendapatan');
$exp=$excel->setActiveSheetIndex(0);
$exp->setCellValue('A1', "Tanggal");
$exp->setCellValue('B1', "EKS");
$exp->setCellValue('C1', "BIS");
$exp->setCellValue('D1', "EKO");
$exp->setCellValue('E1', "L.EKO");
$exp->setCellValue('F1', "Total");
$line=2;
$x=0;
for($i=1;$i<=$tgl[11];$i++){
$exp->setCellValue("A".$line, $i);
$carTL=count($arTL);
$gTGLO=substr($arTL[$x],-2);
if(empty($gTGLO)){
$x=0;
}else{
if($i==$gTGLO){
if(($x+1)>=$carTL){
$x=$carTL-1;
$exp->setCellValue("B".$line, $arLUEKS[$x]);
$exp->setCellValue("C".$line, $arLUBIS[$x]);
$exp->setCellValue("D".$line, $arUEKO[$x]);
$exp->setCellValue("E".$line, $arLEKO[$x]);
$exp->setCellValue("F".$line, $arTot[$x]);
}else{
$exp->setCellValue("B".$line, $arLUEKS[$x]);
$exp->setCellValue("C".$line, $arLUBIS[$x]);
$exp->setCellValue("D".$line, $arUEKO[$x]);
$exp->setCellValue("E".$line, $arLEKO[$x]);
$exp->setCellValue("F".$line, $arTot[$x]);
$x++;
}
}else{
$exp->setCellValue("B".$line, '-');
$exp->setCellValue("C".$line, '-');
$exp->setCellValue("D".$line, '-');
$exp->setCellValue("E".$line, '-');
$exp->setCellValue("F".$line, '-');
}
}
$line++;
}
$excel->getActiveSheet()->setTitle('Laporan');
$excel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="Data Laporan Pendapatan.xlsx');
header('Cache-Control: max-age=0');
$write=PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$write->save('php://output');
Every array like $arLUEKS[$x] is called from database and works, checked with echo
The output is a table with shows data a month from 1 to 31, if the data doesn't exist then it show a -
Anyone can solve this? please help me
I do not know what exactly could be wrong but here are some helpful things you can do that can help you identify your problem .
Turn on error reporting by adding these two to the top of your script
ini_set("display_errors",1);
error_reporting(E_ALL);
This may point you to the cause. Maybe the script is timing out or something
I am using fputcsv for write data. It is working fine. what i need is i need to create another sheet like any name and i need to write data on that. How to do that? Please guide. I am not familiar with this.
This is my code.
$filename = date("Y-m-d").".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: UTF-8");
$fp = fopen('php://output', 'a');
$yetToaproveFields = array('job_no'=>'Job Number',
'revisioncycle'=> 'Revision Cycle',
'version'=>'Version',
'is_approved'=>'Approved Status'
);
fputcsv($fp, $yetToaproveFields);
$notApproveArr = array();
$notApprovedValues = self::getNotApprovedJobs($_REQUEST);
foreach ($notApprovedValues as $key=>$value) {
if ($value['is_approved'] == 1)
$value['is_approved'] = 'No';
fputcsv($fp, $value);
}
fclose($fp);
CSV doesn't support multiple sheets, it's a simple text file. To use sheets, you should use an Excel extension, such as PHPExcel.
You can't.
CSV is a very simple data file format. It doesn't support spreadsheet features like styling or multiple worksheets. If you want multiple worksheets, then you need to use a spreadsheet file format like BIFF (.xls), OfficeOpenXML (.xlsx) or OASIS (.ods)
SITREP
In the middle of building a cart-like document builder/downloader in PHP 5.6.11 and MySqli 5.6.30 on Ubuntu 15.04. A lot of parts work individually but not together.
A database table contains the specific names of products along with corresponding documentation urls (where the PDF's are stored on the server).
Here's the sequence of events, dictated by the end-user's workflow:
Set session cookie. (TBD probably hidden iframe). PHP Page #1.
User searches via form, submits, echos dozens of results + matching url's from the database with checkboxes. PHP Page #1.
User checks a few boxes for items they want to download. PHP Page #1 .
User searches more, check some more items. PHP Page #1.
User hits download button. PHP Page #1.
PHP Page #2 uses the $results['url'] variables from PHP Page #1 in an array, creates a zip, adds files that were checked and prompts download.
I need a solution to pass the returned urls variables $results['url'] from the database search results on PHP #1 into the PHP#2 download processor array.
PHP page #1, query is:
$raw_results = mysql_query("SELECT * FROM mobilesearchspec
WHERE (`url` LIKE '%".$query."%') OR (`product` LIKE '%".$query."%') ORDER BY product ") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
echo "<p><input type=checkbox name=item[] value=$results[url]>" ; echo "".$results['product']."<br>";
echo "<a href='" .$results['url'] . "'>". $results['url'] . "</a>";
Here's the full code of PHP Page #2 processor (from RajdeepPaul's solution below + wiping the zip directory):
$files = $_POST['item'];
$timestamp = date("M-d-Y_H:i:s"); //$timestamp takes the current time
$zipname = "zip_".$timestamp.".zip"; // add timestamp to the file name
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file){
$downloaded_file = file_get_contents($file);
$zip->addFromString(basename($file),$downloaded_file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile("$zipname");
// removes zip file from directory after creation
array_map('unlink', glob("*.pdf"));
array_map('unlink', glob("*.zip"));
I am open to and extremely grateful for any suggestions!
Change your foreach loop in the following way,
foreach ($files as $file){
$downloaded_file = file_get_contents($file);
$zip->addFromString(basename($file),$downloaded_file);
}
So your code on Page #2 should be like this:
$files = $_POST['item'];
$timestamp = date("M-d-Y_H:i:s"); //$timestamp takes the current time
$zipname = "zip_".$timestamp.".zip"; // add timestamp to the file name
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file){
$downloaded_file = file_get_contents($file);
$zip->addFromString(basename($file),$downloaded_file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile("$zipname");
I have troble geting this work and I can't figure it out what is the issue.
I download a xls file, but it doesent opens.
I had a mysql script like this, working, and I tried to convert it into mysqli and probably something is wrong...
Thanks in advance
$sqlExp = "SELECT * FROM table";
$countQryExp = mysqli_query($link, $sqlExp );
$filename = "sampledata.xls"; // File Name
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
while($row=mysqli_fetch_array($countQryExp,MYSQLI_ASSOC))
{
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
There's a lot more to generating an Excel file than giving it a content type of application/vnd.ms-excel. Excel is a very particular format, whereas you're generating a TSV file - tab separated values, and in a pretty breakable manner (what happens if someone puts a \t in one of your site's fields, or a new line?).
If you want to generate real Excel files, you'll want one of the various libraries for doing so. If a CSV/TSV are fine, just export a .csv/.tsv file with proper headers.
basically we currently generate a csv file and push it too the clients browser to download, so no physical files are involved or stored as these are reports that always change.
These have become quite large in some places and I need to reduce the speed and size of the downloads to clients.
I decided to go the zip root and got the below test script working fine, however i am still having to generate the zip file physically and then later delete it, obviously there is a speed factor here as I am writing and reading the file, when I only need to push the zip files contents to the browser.
is there no way to create a stream with the ziplib?
<?php
//report
$reportFilename = 'report';
$data = '005,"756607 ","WED","L","TEST UITENHAGE CBD F NFD"
005,"756608 ","MON","L","TEST SUMMERSTRAND NNB "
005,"756634 ","WED","L","TEST UITENHAGE PENFORD F"
005,"756776 ","MON","L","TEST WALKER DRIVE FOOD "
005,"756858 ","MON","C","TEST R ADAMI&SONS C C "
005,"801002 ","MON","L","TESTMOFFET NNB "
005,"CP00270 ","WED","L","TEST WALMER P FNF "
'; //dummy data
// populate fake data...
$reportData = $data.$data.$data.$data.$data.$data.$data.$data.$data.$data.$data;
//make unique so no clashing occurs
$zipFilename = '_temp_'.microtime().$zipFilename;
//zip data
$zip = new ZipArchive();
$zip->open($zipFilename, ZIPARCHIVE::CREATE);
$zip->addFromString($reportFilename.'.csv' , $reportData); //add report
$zip->close();
$zipData = file_get_contents($zipFilename);
$zipSize = filesize($zipFilename);
unlink($zipFilename);
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=\"".$reportFilename.".zip\"");
header('Content-Transfer-Encoding: binary');
header("Content-Type: application/zip");
echo $zipData;
?>