-1

I want to generate a csv file, using data from a database. How does one do this in PHP CodeIgniter framework?

2

2 Answers 2

1

Take a look at this answer of mine and you will know exactly how you can do it.

Reports in Codeigniter

You need to use Codeigniter Database Utility Class

And need to return query instead of result_array or result

Sign up to request clarification or add additional context in comments.

15 Comments

I used Reports in codeigniter link code but it does not updating my csv. I mentioned CSV file path like this write_file(base_url().'public/csv_file.csv',$new_report);
what do you want to do? generate new csv file or update the existing one
I want to generate new csv
where i have to write this function csv_from_result($report), this was mentioned in codeigniter controller like $new_report = $this->dbutil->csv_from_result($report);
this need to be written in controller as mentioned in example. Just you have to give the correct path. use constant APPPATH and concat where you want to write file
|
1
function query_to_csv( $query, $filename, $attachment = false, $headers = true) {

    if($attachment) {
        // send response headers to the browser
        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment;filename='.$filename);
        $fp = fopen('php://output', 'w');
    } else {
        $fp = fopen($filename, 'w');
    }

    $result = mysql_query($query);

    if($headers) {
        // output header row (if at least one row exists)
        $row = mysql_fetch_assoc($result);
        if($row) {
            fputcsv($fp, array_keys($row));
            // reset pointer back to beginning
            mysql_data_seek($result, 0);
        }
    }

    while($row = mysql_fetch_assoc($result)) {
        fputcsv($fp, $row);
    }

    fclose($fp);
    exit;
}

1 Comment

Stop using mysql_* and OP used Codeigniter, not core php.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.