【问题标题】:Create multiple CSV files from sql statements从 sql 语句创建多个 CSV 文件
【发布时间】:2014-11-11 13:56:44
【问题描述】:

我正在运行如下所示的 sql 来选择我的数据库中具有已定义兴趣代码的所有行。现在我想将所有选择的结果导出到 CSV 中,但这会发生大约 30 次,因为大约有 30 个兴趣代码。有没有办法让我一个接一个地循环遍历 1 个 sql,每次都使用新 SQL 查询的结果创建一个新的 CSV?

两个 sql 查询的示例。

select * from subscribers where list=27 and custom_fields LIKE '%\%CV\%%';
select * from subscribers where list=27 and custom_fields LIKE '%\%JJC\%%';

等等...每次都创建一个全新的 CSV 文件。 30 个文件。

我发现了以下内容(尚未测试),但我想这将是 php,但需要它继续通过 1 个 sql。

$select = "select * from subscribers where list=27 and custom_fields LIKE '%\%CV\%%';";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
    $header .= mysql_field_name( $export , $i ) . "\t";
}

while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {                                            
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                        
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

【问题讨论】:

    标签: php mysql csv


    【解决方案1】:

    我会编写一个创建单个导出的函数,然后在不同代码的循环中调用它。像这样的:

    function export($code)
    {
        $query = "select * from subscribers where list=27 and custom_fields LIKE '%\%" . $code . "\%%'";
        // put the results for this query in $data as in your example
        file_put_contents('/path/to/file/for/code_' . $code, $data);
    }
    
    $codes = array('CV', 'JCC', '...');
    foreach ($codes as $code) {
        export($code);
    }
    

    【讨论】:

    • 我正在尝试如何将您的示例和我的代码放在一起,但还没有完全实现。这是否接近组合所需的内容? pastebin.com/ngQRbJKE
    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2019-01-17
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    相关资源
    最近更新 更多