Ketan Patel

CRUD in CakePHP Part : 1

CRUD in CakePHP


In this post we will see how to create simple CRUD application in CakePHP.If you haven't setup cakephp yet then please read this post How to install CakePHP


Creating Users Database


Let’s set up the database for our blog. Right now, we’ll create a single table for our users. We will add few records of users in order to test. Simply run the SQL query given below into your DB:


/* Create our users table: */
CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(50),
    lastname VARCHAR(50),
    email VARCHAR(50),
    message TEXT
);


/* Then insert some users for testing: */
INSERT INTO users (firstname,lastname,email,message)
    VALUES ('Ricky', 'Astley', 'test1@test.com','Hello...!');
INSERT INTO users (firstname,lastname,email,message)
    VALUES ('John', 'clinton','test2@test.com','How are You...!' );
INSERT INTO users (firstname,lastname,email,message)
    VALUES ('Smith', 'Johnson', 'test3@test.com','I am Fine...!');


Create a User Model


CakePHP’s model class files resides in /app/Model, and the file we’ll be creating will be saved into /app/Model/User.php. The file should look like:


class User extends AppModel {

}

Create a User Controller


Now, we will create a controller of users.All the business logic for user interaction will happen in the controller. This new controller will be placed in a file called UsersController.php inside the /app/Controller directory. Basic controller should look like:


class UsersController extends AppController {
    public $helpers = array('Html', 'Form');
}


Now, lets add one action to our newly created controller. Actions represent a function in an application. For example, when you request : http://yoursite/users/index , users listings will be shown.code for that should look like:


class UsersController extends AppController {
    public $helpers = array('Html', 'Form');
    public function index() {
        $this->set('users', $this->User->find('all'));
    }
 }


Here note the use of set.It will pass the data that we get from the find(all) method to the view(we will create next) file. we can access the data of find(all) method using variable '$users' in the view file.


Creating User Views


Now create a view for the index action that we have created in above step.View files are stored in /app/View inside a folder named like controller(we  have to create a folder having name ‘Users’ in this case).


<!-- File: /app/View/Users/index.ctp -->
<h1>Blog Users</h1>
<table>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Message</th>
    </tr>
    <!-- Here is where we loop through our $users array, printing out user info -->
    <?php foreach ($users as $user): ?>
    <tr>
        <td><?php echo $user['User']['id']; ?></td>
        <td><?php echo $user['User']['firstname'];?></td>     
        <td><?php echo $user['User']['lastname']; ?></td>
        <td><?php echo $user['User']['email']; ?></td>
        <td><?php echo $user['User']['message']; ?></td>
    </tr>
    <?php endforeach; ?>
    <?php unset($user); ?>
</table>



Now go to http://yoursite/users/index. You'll see listing of users, correctly formatted with the title and table listing of the users.


Now what we are going to do is when we click on any particular record it will display all the information of that record.So for that first of all create a new action or you can say it as a function in our controller.


public function view($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid user'));
        }

        $user = $this->User->findById($id);
        if (!$user) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $user);
    }



Here we have used findById() method because we want to display the information for that particular record not for all the records.As we have used $users variable in the index method same here we are using $user variable by using which we can get the data returned by the findById method in view file.


Now create the view for our new ‘view’ action and place it in /app/View/Users/view.ctp

<!-- File: /app/View/Users/view.ctp -->
<h1>First Name:<?php echo h($user['User']['firstname']); ?></h1>
<h1>Last Name: <?php echo $user['User']['lastname'];?></h1>
<h1>Email:<?php echo h($user['User']['email']); ?></h1>
<h1>Message:<?php echo h($user['User']['message']); ?></h1>


To Verify that this is working, click on the links at /users/index or you can manually request a user by going www.example.com/users/view/1.(here 1 is the id of that user.)


We will see the Add,Edit and Delete Functionality in Next Post : CakePHP CRUD Part : 2

Download Demo

ketan patel

About Ketan Patel -

I have developed a wide range of websites using CorePHP, Opencart, CakePHP and CodeIgniter including sites for startup companies and small businesses. Apart from my blogging life, I like to read Novels, Listening music and Net surfing.

Subscribe to this Blog via Email :