Connecting CakePHP 3 To A Database

This quick guide will continue from this setup tutorial, and show you the simple edit you need to make to your CakePHP ‘config.php’ file to connect to you’re database.

This of course will work with any mysql setup, but since we setup our installation on a Digital Ocean Ubuntu server using the PHPMyAdmin one click setup I’ll point out where you can find your mysql user and password info while we’re here.

When you login to you’re server via terminal:

You should be given a welcome message and some info about your setup. You should be able to see something along the lines of the following:

  • The URL to access PHPMyAdmin will be: http://YOUR_IP/phpmyadmin
  • Your user will be: admin
  • Your password will be: Whatever is displayed above

Also not the last line in the above image. There is a ‘.digitalocean_password’ file created in the ‘/root’ directory of your server. If you open that file in a text editor you’ll see that your mysql installation has a few users already configured, one of which will be the same as the user above.

Step 1: Create a Database

First you need you’ll need to login to PHPMyAdmin and create a database for your CakePHP application to use. Once you’ve logged in create a new database by clicking ‘New‘ on the top of the menu on the left of your screen (below):

 

Give your database a name (lowercase, no spaces…obviously), hit ‘Create’, and you’re done here.

Step 2: Update the Config File

You need to connect your CakePHP config file to your new database. The easiest way to do this is to login to your server with FTP software (Filezilla for example).

Once you’re connected navigate to the directory path: /var/www/html/YOUR_APP_NAME/config

In this directory you’ll find an ‘app.php’. This file contains a lot of the general setting for your application, it’s extremely well commented. For now you need to tell it what database to use and the user and password for said database. At the time of writing this in the latest version of CakePHP they are lines 232, 233 and 234. Update the placeholder info with the relevant data and save the file. Upload the new version of that file overwriting the old one, and were done. If you return to the default home page of your application (your IP address if you’ve followed from this setup tutorial), you should now see that your application can talk to your new database.

Time to start making stuff!