CakePHP + MySQL CRUD Example

Hello everyone, today we will learn how to develop a basic User Management Application using CakePHP and MySQL.

-Add User:


-Retrieve all Users:


-Update User:



Step 1 — CakePHP - Environment Setup - click here


Step 2 — Create table_users

CREATE TABLE IF NOT EXISTS tbl_users (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(120) COLLATE utf8_unicode_ci NOT NULL,
email varchar(120) COLLATE utf8_unicode_ci NOT NULL,
phone_no varchar(30) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;



Step 3 — Add CRUD routes[routes.php]

Go to var >> www >> cakephp >> app >> config >> routes.php
<?php

use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;

return static function (RouteBuilder $routes) {
$routes->setRouteClass(DashedRoute::class);

$routes->scope('/', function (RouteBuilder $builder) {

// Users Routes
$builder->connect('/add-user', ['controller' => 'Users',
'action' => 'addUser']);
$builder->connect('/edit-user/:id', ['controller' => 'Users',
'action' => 'editUser'],
["pass" => ["id"]]);
$builder->connect('/delete-user/:id', ['controller' => 'Users',
'action' => 'deleteUser'],
["pass" => ["id"]]);
$builder->connect('/list-users', ['controller' => 'Users',
'action' => 'listUsers']);
});
};



Step 4 — Create UserTable and User Entity

Go to var >> www >> cakephp >> app >> src >> Model >> Table >> UsersTable.php
<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class UsersTable extends Table
{
public function initialize(array $config): void
{
$this->setTable("tbl_users");
}
}

?>

Go to var >> www >> cakephp >> app >> src >> Model >> Entity >> User.php
<?php

namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity
{
protected $_accessible = [
"name" => true,
"email" => true,
"phone_no" => true
];
}

?>



Step 5 — Create the User Controller

Go to var >> www >> cakephp >> app >> src >> Controller >> UsersController.php
<?php

namespace App\Controller;

use App\Controller\AppController;

class UsersController extends AppController
{
public function initialize(): void
{
parent::initialize();
$this->loadModel("Users");
}

public function addUser()
{
$user = $this->Users->newEmptyEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been created.'));
return $this->redirect(['action' => 'listUsers']);
}
$this->Flash->
error(__('Failed to create user. Please, try again.'));
}
$this->set("title", "Add User");
$this->set(compact("user"));
}

public function listUsers()
{
$users = $this->Users->find()->toList();
$this->set("title", "List User");
$this->set(compact("users"));
}

public function editUser($id = null)
{
$user = $this->Users->get($id, [
'contain' => [],
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->
success(__('The user data has been updated successfully.'));

return $this->redirect(['action' => 'listUsers']);
}
$this->Flash->error(__('The user could not be updated.
Please, try again.'));
}
$this->set(compact('user'));
$this->set("title", "Edit User");
}

public function deleteUser($id = null)
{
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success(__('The user has been deleted.'));
} else {
$this->Flash->error(__('The user could not be deleted.
Please, try again.'));
}

return $this->redirect(['action' => 'listUsers']);
}
}

?>


Step 6 — Create View

Go to var >> www >> cakephp >> app >> templates >> Users >> add_user.php

add_user.php.php

<?= $this->Form->create($user, [
"id" => "frm-add-branch"
]) ?>
<div class="row custom-padding">
<div class="col-sm-6">
<!-- text input -->
<div class="form-group">
<label>Name</label>
<input type="text" required class="form-control"
placeholder="Name" name="name">
</div>
</div>
<div class="col-sm-6">
<!-- text input -->
<div class="form-group">
<label>Email</label>
<input type="email" required class="form-control"
placeholder="email" name="email">
</div>
</div>
</div>
<div class="row custom-padding">
<div class="col-sm-6">
<!-- text input -->
<div class="form-group">
<label>Phone No</label>
<input type="text" required class="form-control"
placeholder="Phone No" name="phone_no">
</div>
</div>
</div>


<div class="row custom-padding">
<div class="col-sm-6">
<!-- Select multiple-->
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</div>
</div>
<?= $this->Form->end() ?>



Go to var >> www >> cakephp >> app >> templates >> Users >> edit_user.php

edit_user.php

<?= $this->Form->create($user, [
"id" => "frm-edit-branch"
]) ?>
<div class="row custom-padding">
<div class="col-sm-6">
<!-- text input -->
<div class="form-group">
<label>Name</label>
<input type="text" value="<?= $user->name ?>"
required class="form-control" placeholder="Name" name="name">
</div>
</div>
<div class="col-sm-6">
<!-- text input -->
<div class="form-group">
<label>Email</label>
<input type="email" value="<?= $user->email ?>"
required class="form-control" placeholder="email" name="email">
</div>
</div>
</div>
<div class="row custom-padding">
<div class="col-sm-6">
<!-- text input -->
<div class="form-group">
<label>Phone No</label>
<input type="text" value="<?= $user->phone_no ?>"
required class="form-control"
placeholder="Phone No" name="phone_no">
</div>
</div>
</div>


<div class="row custom-padding">
<div class="col-sm-6">
<!-- Select multiple-->
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</div>
</div>
<?= $this->Form->end() ?>


Go to var >> www >> cakephp >> app >> templates >> Users >> list_users.php

list_users.php

<table id="tbl-users-list" class="table table-bordered table-striped">
<thead>
<tr>
<td colspan="5" align="right"><a href="<?= $this->
Url->build('/add-user/', ['fullBase' => true]) ?>">
Add User</a></td>
</tr>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone No</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if (count($users) > 0) {
foreach ($users as $index => $data) {
?>
<tr>
<td><?= $data->id ?></td>
<td><?= $data->name ?></td>
<td><?= $data->email ?></td>
<td><?= $data->phone_no ?></td>
<td>
<a href="<?= $this->Url->build('/edit-user/' . $data->id,
['fullBase' => true]) ?>" class="btn btn-warning">Edit</a>
<a href="<?= $this->Url->build('/delete-user/' . $data->id,
['fullBase' => true]) ?>" class="btn btn-warning">Delete</a>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>



Step 7 — Start the development server

    $ cd /var/www/cakephp/app 

    sudo bin/cake server

    Open your web browser and access http://localhost:8765/list-users

    Comments

    Popular posts from this blog

    Learn Java 8 streams with an example - print odd/even numbers from Array and List

    Java, Spring Boot Mini Project - Library Management System - Download

    Java - Blowfish Encryption and decryption Example

    Java - DES Encryption and Decryption example

    Google Cloud Storage + Spring Boot - File Upload, Download, and Delete

    ReactJS - Bootstrap - Buttons

    Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

    File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

    Top 5 Java ORM tools - 2024

    Java - How to Count the Number of Occurrences of Substring in a String