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 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站