CakePHP 4 Export MySQL Table Data into CSV File Tutorial

Reading Time: 6 minutes

Inside this article we will see the concept of CakePHP 4 Export MySQL Table Data into CSV File format. Article contains the classified information about this topic. You will get the whole idea to dump your database data into CSV file.

If we have an application which basically built for reporting then we need some kind of function which export tabular data into CSV format.

In this article we will export data from table employees. Employees table will have the columns and their attributes as –

  • id [INTEGER]
  • name [STRING]
  • email [STRING]
  • mobile [STRING]

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.


Successfully, we have created a database.

Database Connection

Open app_local.php file from /config folder. Search for Datasources. Go to default array of it.

You can add your connection details here to connect with your database. It will be like this –


'Datasources' => [
        'default' => [
            'host' => 'localhost',
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
            //'port' => 'non_standard_port_number',

            'username' => 'root',
            'password' => 'sample@123',

            'database' => 'mydatabase',
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
            //'schema' => 'myapp',

             * You can use a DSN string to set the entire configuration
            'url' => env('DATABASE_URL', null),


You can pass host, username, password and database.

Successfully, you are now connected with the database.

Create Migration

Let’s create a migration file for “employees” table.

Open project into terminal and run this command

$ bin/cake bake migration CreateEmployees

This command will create a migration file inside /config/Migrations folder. File name will be prefixed with the timestamp value and look like 20220217021429_CreateEmployees.php

Open migration file and write this code into it to create “employees” table schema.



use Migrations\AbstractMigration;

class CreateEmployees extends AbstractMigration
     * Change Method.
     * More information on this method is available here:
     * @return void
    public function change()
        $table = $this->table('employees');

        $table->addColumn('name', 'string', [
            'limit' => 120,
            'null' => false,
        $table->addColumn('email', 'string', [
            'limit' => 50,
            'null' => false,
         $table->addColumn('mobile', 'string', [
            'limit' => 30,
            'null' => false,

Run Migration

Open terminal and run this command to create table schema.

$ bin/cake migrations migrate

It will create employees table in database.

Let’s consider Test data into table.

Sample Data Rows


We will insert some fake rows into table. There are multiple ways to insert fake rows – Using Seeder, Using Raw Query.

We will dump fake employees using a mysql query into employees table.

-- Dumping data for table `employees`

INSERT INTO `employees` (`id`, `name`, `email`, `mobile`) VALUES
(1, 'Sanjay Kumar', '', '1234567895'),
(2, 'Ashish Kumar', '', '7412589635'),
(3, 'Vijay Kumar', '', '9632587410'),
(4, 'Dhananjay Negi', '', '8529637410'),
(5, 'Ajit Kumar', '', '9658741230'),
(6, 'Suman Yadav', '', '2635897410'),
(7, 'Mandeep Singh', '', '8526937410'),
(8, 'Sourav Sukhla', '', '8974563210'),
(9, 'Raman Singh', '', '8596347158'),
(10, 'Suneel Rana', '', '1547896304'),
(11, 'Vikram Singh', '', '8526934710');

You will see, table will look like this after successful insertion.

Now, we need to dump these data into CSV format. You can consider your own data in application.

Create Model & Entity


We will create model and entity. Back to terminal and run this command.

$ bin/cake bake model Employees --no-validation --no-rules

It will create model file EmployeesTable.php inside /src/Model/Table folder. Also we should see the entity file Employee.php inside /src/Model/Entity folder.

Create Controller

Open project into terminal and run this command into it.

$ bin/cake bake controller Site --no-actions

It will create SiteController.php file inside /src/Controller folder. Open controller file and write this code into it.



namespace App\Controller;

class SiteController extends AppController
    public function initialize(): void


    public function downloadCSVReport()
        $this->autoRender = false;

        $employees = $this->Employees->find()->toList();

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=employees-' . date("Y-m-d-h-i-s") . '.csv');
        $output = fopen('php://output', 'w');
        fputcsv($output, array('Id', 'Name', 'Email', 'Mobile'));

        if (count($employees) > 0) {

            foreach ($employees as $employee) {

                $employee_row = [

                fputcsv($output, $employee_row);

Add Route

Open routes.php file from /config folder. Add this route into it.


    ['controller' => 'Site', 'action' => 'downloadCSVReport']


Application Testing

Open terminal and run this command to start development server.

$ bin/cake server

URL: http://localhost:8765/download-csv

When you hit above URL, it will download a CSV file with name employees-{datetime}.csv

We hope this article helped you to learn about CakePHP 4 Export MySQL Table Data into CSV File Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more