zip csv and image files from SQL using php-ThrowExceptions

Exception or error:

I have a table which contains sample No. density and sample_image column. Currently, I’m able to generate a CSV file with sample No. and density data.

Now I want to also download sample_images that are linked to the sample_no. and Zip the CSV file together with the images. I not very sure how to integrate the zip function into my current CSV export. I have googled about PHP zip but still very confuse… Can anyone help? Below are codes:

PHP code

if($_GET['exportdata'] == 'true'){

    $filename = "data.csv"; // Create file name


    $f = fopen('php://memory', 'w');

        //Column name in csv file
        $fields = array('Sample No.',
            'Density');

        fputcsv($f, $fields);

    //SQL statement
    $query = "SELECT [SampleNo], [Density], [Sample_image] FROM SAMPLE";

    //execute SQL statement
    $stmt = sqlsrv_query($conn, $query);

    //extract data from SQL statement
    while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC)){

            $row[0]; 
            $row[1]; 
            $row[2]; //image file name

        fputcsv($f, $row);

    }

    //move back to beginning of file
    fseek($f, 0);

    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');

    //output all remaining data on a file pointer
    fpassthru($f);

 }

Sample table in SQL database:
enter image description here

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *