Working with Database

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

Further, we also need to configure our database in config/app_local.php file.

'Datasources' => [
   'default' => [
      'host' => 'localhost',
      'username' => 'my_app',
      'password' => 'secret',
      'database' => 'my_app',
      'url' => env('DATABASE_URL', null),
   ],
   /*
      * The test connection is used during the test suite.
   */
   'test' => [
      'host' => 'localhost',
      //'port' => 'non_standard_port_number',
      'username' => 'my_app',
      'password' => 'secret',
      'database' => 'test_myapp',
      //'schema' => 'myapp',
   ],
],

The default connection has following details −

'host' => 'localhost',
   'username' => 'my_app',
   'password' => 'secret',
   'database' => 'my_app',

You can change the details, i.e. host, username, password and database as per your choice.

Once done, make sure it is updated in config/app_local.php in Datasources object.

Now, we will continue with above details, go to your phpmyadmin or mysql database and create user my_app as shown below −

My App

Give the necessary privileges and save it. Now, we have the database details as per the configuration mentioned in app_local.php. When you check CakePHP home page, this is what you should get −

App Local

Now, we will create the following users’ table in the database.

CREATE TABLE `users` ( 
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `username` varchar(50) NOT NULL, 
   `password` varchar(255) NOT NULL, PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1

Insert a Record

To insert a record in database, we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as an argument.

This new instance is used to create new entity. Set necessary values with the instance of new entity. We now have to call the save() method with TableRegistry class’s instance which will insert new record in database.

Example

Make changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('/users/add', ['controller' => 'Users', 'action' => 'add']);
   $builder->fallbacks();
});

Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file.

src/controller/UsersController.php

<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Auth\DefaultPasswordHasher;
class UsersController extends AppController{
   public function add(){
      if($this->request->is('post')){
         $username = $this->request->getData('username');
         $hashPswdObj = new DefaultPasswordHasher;
         $password = $hashPswdObj->hash($this->request->getData('password'));
         $users_table = TableRegistry::get('users');
         $users = $users_table->newEntity($this->request->getData());
         $users->username = $username;
         $users->password = $password;
         $this->set('users', $users);
         if($users_table->save($users))
         echo "User is added.";
      }
   }
}
?>

Create a directory Users at src/Template and under that directory create a View file called add.php. Copy the following code in that file.

src/Template/Users/add.php

<?php
   echo $this->Form->create(NULL,array('url'=>'/users/add'));
   echo $this->Form->control('username');
   echo $this->Form->control('password');
   echo $this->Form->button('Submit');
   echo $this->Form->end();
?>

Execute the above example by visiting the following URL. http://localhost/cakephp4/users/add

Output

Upon execution, you will receive the following output.

Added

The data will be saved in the users table as shown below −

Show All

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *