[英]Query mysql, place empty fields, and export data as CSV using PHP
What would be the best approach to create a CSV file that contains 100+ fields where only 1/3 is actually being used? 创建包含100个以上仅实际使用1/3个字段的CSV文件的最佳方法是什么?
A simple example is (bear with me): 一个简单的例子是(与我同在):
If I have a 5 column table (X,O,#,T,P) with X amount of rows and the csv format needs to be 如果我有一个5列的表(X,O,#,T,P),其行数为X,并且csv格式需要为
X,,,,O,,,,T,P,,,,,,#,,,
Thanks! 谢谢!
您可以使用mysql查询直接将表数据导出到csv文件
"SELECT column1, column2, column3 INTO OUTFILE '<filename>' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\' LINES TERMINATED BY '\r\n' FROM table1;"
One approach is you can place dummy columns in select
query itself and then just create a CSV
from the output: 一种方法是,您可以在
select
查询本身中放置虚拟列,然后从输出中创建CSV
:
select X,'','','',O,'','','',T,P,'','','','','',#,'','' from table_name; // this will by default give you your CSV structured output.
$fp = fopen('file_name', 'w');
fputcsv($fp, $values);
You can create lots of empty fields in the SELECT
clause 您可以在
SELECT
子句中创建许多空字段
SELECT X, '' AS col2, '' AS col3, '', O, '', '', '', '', T, P, '', '', '', '', '', '', `#`, '', ''
INTO OUTFILE 'filename.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM yourTable;
When reading the file back into the table, you can specify which fields of the file go into the table like this: 将文件读回到表中时,可以指定文件的哪些字段进入表,如下所示:
LOAD DATA INFILE 'filename.csv'
INTO TABLE yourTable
(X, @dummy, @dummy, @dummy, O, @dummy, @dummy, @dummy, @dummy, T, P, @dummy, @dummy, @dummy, @dummy, @dummy, @dummy, `#`, @dummy, @dummy);
The @dummy
variables receive the values of those file fields, while the column names receive those file fields. @dummy
变量接收那些文件字段的值,而列名接收那些文件字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.