I have a mysql statement and I would like to store the data it fetches in a csv file in tab format. I have used the following statment but it is not creating and storing the results when I run my file and no error files.
$mytry = "SELECT * FROM table WHERE `assigned` = '$id'
INTO OUTFILE '/inactive/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
LINES TERMINATED BY '\n'";
mysql_query($mytry);
Or there a way I can write to file in a directory without prompting the user to download, this works but it prompts
$sQuery="SELECT * FROM table WHERE `assigned` = '$id'";
$rResult = mysql_query( $sQuery) or die();
$count = mysql_num_fields($rResult);
$html = '<table border="1"><thead><tr>%s</tr><thead><tbody>%s</tbody></table>';
$thead = '';
$tbody = '';
$line = '<tr>%s</tr>';
for ($i = 0; $i < $count; $i++){
$thead .= sprintf('<th>%s</th>',mysql_field_name($rResult, $i));
}
while(false !== ($row = mysql_fetch_row($rResult))){
$trow = '';
foreach($row as $value){
$trow .= sprintf('<td>%s</td>', $value);
}
$tbody .= sprintf($line, $trow);
}
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: filename=exportfile.xls");
header("Pragma: no-cache");
header("Expires: 0");
print sprintf($html, $thead, $tbody);
exit;
You might want to look into the following PHP function: http://php.net/manual/en/function.fputcsv.php
Fetch the data using your query and then save it to a variable. Then, use fputcsv to store the data to a file.
Also, I would discourage the usage of mysql_query, since it has now become deprecated (as well as the rest of mysql_* family). Furthermore, your code is vulnerable to SQL injection attacks. Read up on using PDO for database interaction.
Some more recommended reading to put you on the right track: http://www.phptherightway.com/#databases
EDIT: From what you have shown in your code sample, you simply output an HTML page to the browser, which gets downloaded right away because of the Content-Disposition header you set.
Related
I am trying to download table data into a CSV format. The data in one of the fields contains ",".
Eg: Doe, John
When I download the csv file, the data after comma is shifted to next column. But I want the entire data i.e including comma in same column.
The Code I used as follows:
<?php
include('dbconfig.php');
//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=download.csv');
//select table to export the data
$sql ="SELECT * FROM tablename";
$select_table=mysqli_query($db, $sql);
$rows = mysqli_fetch_assoc($select_table);
if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysqli_fetch_assoc($select_table);
}
// get total number of fields present in the database
function getcsv($no_of_field_names)
{
$separate = '';
// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace('<em>', '', $field_name) . '';
}
echo $separate . $field_name;
//sepearte with the comma
$separate = ',';
}
//make new row and line
echo "\r\n";
}
?>
Can someone help me get through this issue.
Thanks
Make sure you escape the ,. Typically values that contain sensitive characters (such as , and \n) are surrounded in ".
So your output can be:
"Doe, John",52,New York
You can either write your own escape function or use PHPs fputcsv. It writes to a file handler that's a bit inconvenient but you can make it stdout.
$handle = fopen("php://stdout");
fputcsv($handle, array("Doe, John", 52, "New York"));
I create a csv file with the SQL query:
$sql = "SELECT 'id','username','name','email',
'phone_number','city',
'batch','course_type' UNION ALL
SELECT id, username, name, email,
phone_number, city, batch, course_type
FROM users INTO OUTFILE '".$file_path."' ".
"FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
LINES TERMINATED BY '\n'";
After causing a browser force-download of this file, I need to delete this file from the /tmp directory. But since, the file is owned by mysql, the php code cannot delete it. How do I change permissions on this file in my code so that the file can be deleted?
One solution to do this right, is (This is a rough example of how it could be done):
Return the data from the database as an array, and iterate through it:
// tell the browser that this is a download
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=list.csv");
// column separator
$separator = ';';
// field delimiter
$field_delimiter = '"';
// line end
$line_end = "\r\n";
foreach ($result as $row):
$i = 0;
foreach ($row as $item):
// do not add separator before the first item
if ($i > 0)
{
echo $separator;
}
echo $field_delimiter.$item.$field_delimiter;
$i++;
endforeach;
// line end
echo $line_end;
endforeach;
Do not output anything else, just the CSV content.
Everything works perfectly but I've encountered a problem when I'm exporting data to a CSV file. I tried searching for similar problems but I didn't quite find any that could be relevant to my problem.
This code here is supposed to export the whole database table from mySQL database. It does it perfectly but the thing is, it puts all the data in the first column - in different cells.
The cell placement is alright but it's supposed to spread the data over several columns (13 in my case).
Here's the screenshot to explain what's happening:
Code:
<?php
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: filename=export.csv");
#$query=mysql_query("set names 'utf8'");
#mb_http_output('UTF-8');
#mb_http_input('UTF-8');
#mb_language('uni');
#mb_regex_encoding('UTF-8');
#ob_start('mb_output_handler');
#header('Content-type: text/html; charset=utf-8');
$conn = mysql_connect('localhost', 'root', 'asdasd') or die(mysql_error());
mysql_select_db('nooruse', $conn) or die(mysql_error($conn));
$query = sprintf('SELECT osakond as Osakond, soetusaasta as Soetusaasta, it_number as IT_Number, tooteruhm as Tooteruhm, mudeli_nimetus as Mudeli_nimetus, sn as SN, riigivara_nr as Riigivara_nr, inventaari_nr as Inventari_nr, maja as Maja, ruum as Ruum, vastutaja as Vastutaja, markus as Markus,kasutajanimi as Kasutajanimi FROM norse5_proov');
$result = mysql_query($query, $conn) or die(mysql_error($conn));
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
Thanks in advance.
The problem is you are assuming that Excel knows that a semicolon is the separator.
For some machines this might work, others not.
It was suggested this has to do with regional setting in the control panel under List Separator.
I found a suggestion to add the following as the first line of the CSV to tell excel what separator to use:
sep=;
Haven't tried this, but it seems legit.
Here is a link to a better description (see the 3rd comment down for the way to set the separator in the CSV file to avoid client computer changes):
Trouble with Opening CSV Files with Excel? The Comma and Semicolon Issue in Excel due to Regional Settings for Europe
I am exporting content from an MySQL database to a Word Template (RTF) via PHP.
There is a section, "Appendix B", which should display all the Acronyms found for a record. The minimum records to appear for this section is 90 (i.e. these are standard acronyms (tblAcronyms) that each record will have); however the maximum records are unknown since users can add to this listing (tblAppendixB).
The Word (i.e. RTF) document should display all the records found, however, it is only displaying the first record.
This is what I have thus far:
<?php
....
#Retrieve Appendix B records
$qry_get_AppB = "SELECT vAcronym, vAcronymDesc FROM tblAcronyms
UNION SELECT vAcronym, vAcronymDesc FROM tblAppendixB
WHERE fkID = ". $i_fk_id . " ORDER BY vAcronym ASC";
$qry_appb_result = mysql_query($qry_get_AppB);
$qryAppBno_rows = mysql_num_rows($qry_appb_result);
//Generate the headers to help a browser choose the correct location
header('Content-Type: application/msword');
header('Content-Disposition: inline; filename="'.$vProgramName.'_rec.rtf");
//Open the template file
$tfilename = 'Appb_Template.rtf';
$fp = fopen($tfilename, 'r');
//Read the template into a variable
$toutput = fread($fp, filesize($tfilename));
fclose($fp);
//Replace the place holders in the template with data
if($qryAppBno_rows > 0)
{
while($rowAppB = mysql_fetch_array($qry_appb_result))
{
$vAppB = $rowAppB['vAcronym'] . '-' . $rowAppB['vAcronymDesc'] . "\r\n";
$toutput = str_replace('<<vAppB>>', $vAppB, $toutput);
}
}
//Send the generated document to the browser
echo $toutput;
?>
I have searched this forum and others but have yet to find a solution.
Any assistance is greatly appreciated.
Okay, I'm not quite sure what your template looks like, but I guess, you only have 1 place holder named <<vAppB>>. In your 1st iteration (if there is any data available) you replace that placeholder with your 1st data entry. In this fact only one placeholder is shown.
May rewrite your code to something similar to this
... //do your stuff
$newLine = "\r\n";
$appendix = "";
while($rowAppB = mysql_fetch_array($qry_appb_result)) {
$appendix .= $rowAppB['vAcronym'] . '-' . $rowAppB['vAcronymDesc'] . $newLine;
}
$toutput = str_replace('<<vAppB>>', $appendix, $toutput);
...//do some other stuff
Just simple prototyping, so you may have to do some additional work.
The trick is to collect all entries you got and than replace it with your placeholder :)
I resolved the problem; I had to use "\par" instead of "\r\n" for MS Word (RTF) to recognize it as a paragraph mark. Here is the modified code that now works:
<?php
....
$t_newline = "\par";
#Retrieve Appendix B records
$qry_get_AppB = "SELECT vAcronym, vAcronymDesc FROM tblAcronyms
UNION SELECT vAcronym, vAcronymDesc FROM tblAppendixB
WHERE fkID = ". $i_fk_id . " ORDER BY vAcronym ASC";
$qry_appb_result = mysql_query($qry_get_AppB);
$qryAppBno_rows = mysql_num_rows($qry_appb_result);
//Generate the headers to help a browser choose the correct location
header('Content-Type: application/msword');
header('Content-Disposition: inline; filename="'.$vProgramName.'_rec.rtf");
//Open the template file
$tfilename = 'Appb_Template.rtf';
$fp = fopen($tfilename, 'r');
//Read the template into a variable
$toutput = fread($fp, filesize($tfilename));
fclose($fp);
//Replace the place holders in the template with data
if($qryAppBno_rows > 0)
{
while($rowAppB = mysql_fetch_array($qry_appb_result))
{
$vAppendixB[] = $rowAppB['vAcronym'] . '-' . $rowAppB['vAcronymDesc'] . $t_newline;
$vAppB = implode(" ", $vAppendixB);
}
}
$toutput = str_replace('<<vAppB>>', $vAppB, $toutput);
//Send the generated document to the browser
echo $toutput;
?>
Hopefully this will help someone else. :-)
I'm trying to convert some MYSQL querys to MYSQLI, but I'm having an issue, below is part of the script I am having issues with, the script turn a query into csv:
$columns = (($___mysqli_tmp = mysqli_num_fields($result)) ? $___mysqli_tmp : false);
// Build a header row using the mysql field names
$rowe = mysqli_fetch_assoc($result);
$acolumns = array_keys($rowe);
$csvstring = '"=""' . implode('""","=""', $acolumns) . '"""';
$header_row = $csvstring;
// Below was used for MySQL, Above was added for MySQLi
//$header_row = '';
//for ($i = 0; $i < $columns; $i++) {
// $column_title = $file["csv_contain"] . stripslashes(mysql_field_name($result, $i)) . $file["csv_contain"];
// $column_title .= ($i < $columns-1) ? $file["csv_separate"] : '';
// $header_row .= $column_title;
// }
$csv_file .= $header_row . $file["csv_end_row"]; // add header row to CSV file
// Build the data rows by walking through the results array one row at a time
$data_rows = '';
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < $columns; $i++) {
// clean up the data; strip slashes; replace double quotes with two single quotes
$data_rows .= $file["csv_contain"] .$file["csv_equ"] .$file["csv_contain"] .$file["csv_contain"] . preg_replace('/'.$file["csv_contain"].'/', $file["csv_contain"].$file["csv_contain"], stripslashes($row[$i])) . $file["csv_contain"] .$file["csv_contain"] .$file["csv_contain"];
$data_rows .= ($i < $columns-1) ? $file["csv_separate"] : '';
}
$data_rows .= $this->csv_end_row; // add data row to CSV file
}
$csv_file .= $data_rows; // add the data rows to CSV file
if ($this->debugFlag) {
echo "Step 4 (repeats for each attachment): CSV file built. \n\n";
}
// Return the completed file
return $csv_file;
The problem I am having is when building a header row for the column titles mysqli doesn't use field_names so I am fetching the column titles by using mysqli_fetch_assoc() and then implode() the array, adding the ,'s etc for the csv.
This works but when I produce the csv I am deleting the first data row when the header is active, when I remove my header part of the script and leave the header as null I get all data rows and a blank header (As expected).
So I must be missing something when joining my header to array to the $csv_file.
Can anyone point me in the right direction?
Many Thanks
Ben
A third alternative is to refactor the loop body as a function, then also call this function on the first row before entering the loop. You can use fputcsv as this function.
$csv_stream = fopen('php://temp', 'r+');
if ($row = $result->fetch_assoc()) {
fputcsv($csv_stream, array_keys($row));
fputcsv($csv_stream, $row);
while ($row = $result->fetch_row()) {
fputcsv($csv_stream, $row);
}
fseek($csv_stream, 0);
}
$csv_data = stream_get_contents($csv_stream);
if ($this->debugFlag) {
echo "Step 4 (repeats for each attachment): CSV file built. \n\n";
}
// Return the completed file
return $csv_data;
As this basically does the same thing as a do ... while loop, which would make more sense to use. I bring up this alternative to present the loop body refactoring technique, which can be used when a different kind of loop doesn't make sense.
Best of all would be to use both mysqli_result::fetch_fields and fputcsv
$csv_stream = fopen('php://temp', 'r+');
$fields = $result->fetch_fields();
foreach ($fields as &$field) {
$field = $field->name;
}
fputcsv($csv_stream, $fields);
while ($row = $result->fetch_row()) {
fputcsv($csv_stream, $row);
}
fseek($csv_stream, 0);
$csv_data = stream_get_contents($csv_stream);
if ($this->debugFlag) {
echo "Step 4 (repeats for each attachment): CSV file built. \n\n";
}
// Return the completed file
return $csv_data;
If you can require that PHP be at least version 5.3, you can replace the foreach that generates the header line with a call to array_map. There admittedly isn't much advantage to this, I just find the functional approach more interesting.
fputcsv($csv_stream,
array_map(function($field) {return $field->name},
$result->fetch_fields()));
As you observe, you're using the first row to obtain the field names but then not using the data from the row. Evidently, you need to change your code so that you get both of those things.
There are a number of ways you might do this. The most appropriate one is to use mysqli_fetch_fields() instead to get the field metadata from the result object.
http://www.php.net/manual/en/mysqli-result.fetch-fields.php
Alternatively, you could make the loop lower down in the code a do... while instead of a while.