CakePHP 4 Export MySQL Table Data into CSV File Tutorial

Reading Time: 6 minutes
3,037 Views

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.

CREATE DATABASE mydatabase;

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.

<?php

declare(strict_types=1);

use Migrations\AbstractMigration;

class CreateEmployees extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     * @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,
        ]);
      
        $table->create();
    }
}

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

Here,

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', 'sanjay@gmail.com', '1234567895'),
(2, 'Ashish Kumar', 'ashish@gmail.com', '7412589635'),
(3, 'Vijay Kumar', 'vijay@gmail.com', '9632587410'),
(4, 'Dhananjay Negi', 'dj@gmail.com', '8529637410'),
(5, 'Ajit Kumar', 'ajit@gmail.com', '9658741230'),
(6, 'Suman Yadav', 'suman@gmail.com', '2635897410'),
(7, 'Mandeep Singh', 'mandeep@gmail.com', '8526937410'),
(8, 'Sourav Sukhla', 'sukhla.sourav@gmail.com', '8974563210'),
(9, 'Raman Singh', 'raman001@gmail.com', '8596347158'),
(10, 'Suneel Rana', 'suneel@gmail.com', '1547896304'),
(11, 'Vikram Singh', 'vikram@gmail.com', '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

Next,

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.

<?php

declare(strict_types=1);

namespace App\Controller;

class SiteController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        $this->loadModel("Employees");
    }

    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 = [
                    $employee['id'],
                    ucfirst($employee['name']),
                    $employee['email'],
                    $employee['mobile']
                ];

                fputcsv($output, $employee_row);
            }
        }
    }
}

Add Route

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

//...

$routes->connect(
    '/download-csv',
    ['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.