Skip to content
Advertisement

Why can’t I export MySQL table values as a CSV file in this Codeigniter application?

I have been developing a blogging application with CodeIgniter 3.1.8 and Twig.

The application has a newsletter subscription system. I make use of a table named newsletter with 3 columns: id, email and subscription_date.

In the class Subscribers controller, I have created an export() method intend to export subscribers as a CSV file:

JavaScript

In the Newsletter_model model:

JavaScript

The export form:

JavaScript

The problem

For a reason I have not been able to figure out, only the table headers are exported, not the values (emails and dates).

What am I doing wrong?

Advertisement

Answer

Ok, here’s what I found by replicating your code to a fresh install of Codeigniter.

  1. Created a “files” directory on project root
  2. I’ve autoloaded the “database” library and the “url” helper;
  3. Created a newsletter table, as described by you, using mockaroo;
  4. I’m not considering the request headers, download or redirect, as they didn’t seemed wrong to me
  • Nothing was changed on the Newsletter_model, just on the controller.

Here’s my export()

JavaScript

What happened is:

  1. Your model returns an Array with objects. So, your $row will be a object.
  2. fputcsv expects an Array as a second parameter, just like you did with the $header

I think this will work for you. 🙂

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement