wharfdale
wharfdale

Reputation: 752

Create multiple CSV files from sql statements

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 ) . "\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";

Upvotes: 0

Views: 1113

Answers (1)

Alex Howansky
Alex Howansky

Reputation: 53553

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);
}

Upvotes: 2

Related Questions