0

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";

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm trying to piece how to put your example and my code together but not quite getting there. Is this close to what is required in combination? pastebin.com/ngQRbJKE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.