2

如何使用 php 将 mysql 数据表搜索查询导出到 csv?

听到是查询

if ($_REQUEST["startfrom"]<>'' and $_REQUEST["end"]<>'') {
    $sql = "SELECT ECRNo,SalesDate,TimeSold,AmountDue,OutletName,ProductCode,Category,MealType,SUM(Quantity) AS Quantity1,SUM(NetPrice) AS NetPrice1 FROM ".$SETTINGS["data_table"]." WHERE SalesDate BETWEEN '".mysql_real_escape_string($_REQUEST["startfrom"])."'And'".mysql_real_escape_string($_REQUEST["end"])."'".$search_OutletName.$search_Category.$search_ProductCode.$search_groupby;
} else if ($_REQUEST["startfrom"]<>'') {
    $sql = "SELECT ECRNo,SalesDate,TimeSold,AmountDue,SalesDate,OutletName,ProductCode,Category,MealType,SUM(Quantity) AS Quantity1,SUM(NetPrice) AS NetPrice1 FROM ".$SETTINGS["data_table"]." WHERE SalesDate >= '".mysql_real_escape_string($_REQUEST["startfrom"])."'".$search_OutletName.$search_Category.$search_ProductCode.$search_groupby;
} else if ($_REQUEST["end"]<>'') {
    $sql = "SELECT ECRNo,SalesDate,TimeSold,SalesDate,AmountDue,OutletName,ProductCode,Category,MealType,SUM(Quantity) AS Quantity1,SUM(NetPrice) AS NetPrice1 FROM ".$SETTINGS["data_table"]." WHERE SalesDate <= '".mysql_real_escape_string($_REQUEST["end"])."'".$search_OutletName.$search_Category.$search_ProductCode.$search_groupby;
}else {
    $sql = "SELECT ECRNo,SalesDate,TimeSold,SalesDate,AmountDue,OutletName,ProductCode,Category,MealType,SUM(Quantity) AS Quantity1,SUM(NetPrice) AS NetPrice1 FROM ".$SETTINGS["data_table"]." WHERE ECRNo>0 ".$search_OutletName.$search_Category.$search_ProductCode.$search_groupby;
}

如何导出其查询结果?

4

4 回答 4

6

这里有所有好的答案,但如果你想使用 PHP 来做,这里是另一种选择:

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

$list 数组将是您从数据库中获取的结果。

取自这里

于 2013-11-13T09:13:12.897 回答
5

来自 http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/

SELECT *
FROM tableName
INTO OUTFILE '/tmp/fileName.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
于 2013-09-11T09:13:29.170 回答
2

这是完美的工作,请试试这个...

SELECT * INTO OUTFILE "Database/business.sql"
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' 
FROM `business`

谢谢你。

于 2013-11-13T08:59:20.387 回答
0

您可以使用 mysql 功能:

SELECT * FROM tableName INTO OUTFILE 'filename.csv' 

. 我认为它应该工作

于 2013-09-11T09:05:33.530 回答