dongpan3001 2014-11-11 13:56
浏览 42
已采纳

从sql语句创建多个CSV文件

I am running the sql as shown below to select all rows in my database which has the defined Interest Code. Now I'd like to export all the selected results into a CSV, but this is to happen about 30 times as there are about 30 interest codes. Is there a way for me to loop through 1 sql after another, each time creating a new CSV with the results of the new SQL query?

Example of two of the sql queries.

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

and so on... Each time creating an entirely new CSV file. 30 files.

I've found the following (untested yet) but I suppose this would be the php but with the need for it to keep going through 1 sql after another.

$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 ) . "
";
}
$data = str_replace( "" , "" , $data );

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

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

1条回答 默认 最新

  • duancan1950 2014-11-11 15:36
    关注

    I'd write a function that creates a single export and then call that in a loop of the different codes. Something like this:

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计