Tutorial Codeigniter 4 || 4. Cara Membuat CRUD Dengan MySQL dan Codeigniter 4

3 min read 7 months ago
Published on Aug 24, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will learn how to create a complete CRUD (Create, Read, Update, Delete) application using CodeIgniter 4 and MySQL. CodeIgniter 4 is a popular PHP framework that simplifies web development. This guide will provide step-by-step instructions to help you manage database operations effectively.

Step 1: Setting Up Your Environment

To begin, ensure you have the following prerequisites:

  • XAMPP installed on your machine for running PHP and MySQL.
  • CodeIgniter 4 downloaded from the official website.

Installation

  1. Download CodeIgniter 4 from the CodeIgniter website.
  2. Extract the files into the htdocs directory of your XAMPP installation.
  3. Open your web browser and navigate to http://localhost/phpmyadmin to access the MySQL management interface.

Database Creation

  1. Create a new database for your application. For example, name it crud_db.
  2. Create a table named users with the following fields:
    • id (INT, Auto Increment, Primary Key)
    • name (VARCHAR)
    • email (VARCHAR)
    • created_at (DATETIME)

Step 2: Configuring CodeIgniter

After setting up your database, you need to configure CodeIgniter to connect to your MySQL database.

Database Configuration

  1. Open app/Config/Database.php.
  2. Modify the database settings as follows:
    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'crud_db',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'cacheOn'  => false,
        'cachedir' => '',
        'charSet'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'saveQueries' => true,
    ];
    

Step 3: Creating the Model

In CodeIgniter, models are used to interact with the database.

User Model Creation

  1. Create a new file UserModel.php in the app/Models directory.
  2. Add the following code:
    namespace App\Models;
    
    use CodeIgniter\Model;
    
    class UserModel extends Model {
        protected $table = 'users';
        protected $primaryKey = 'id';
        protected $allowedFields = ['name', 'email', 'created_at'];
    }
    

Step 4: Creating the Controller

Controllers handle requests and responses in CodeIgniter.

User Controller Creation

  1. Create a new file User.php in the app/Controllers directory.
  2. Add the following code:
    namespace App\Controllers;
    
    use App\Models\UserModel;
    
    class User extends BaseController {
        public function index() {
            $model = new UserModel();
            $data['users'] = $model->findAll();
            return view('user_view', $data);
        }
    
        public function create() {
            return view('create_user');
        }
    
        public function store() {
            $model = new UserModel();
            $data = [
                'name' => $this->request->getPost('name'),
                'email' => $this->request->getPost('email'),
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $model->save($data);
            return redirect()->to('/user');
        }
        
        // Additional methods for updating and deleting users can be added here.
    }
    

Step 5: Creating Views

Views are used to display the user interface.

User View

  1. Create a file named user_view.php in the app/Views directory.
  2. Add the following code to display users:
    <h1>User List</h1>
    <a href="/user/create">Add User</a>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        <?php foreach ($users as $user): ?>
        <tr>
            <td><?= $user['id'] ?></td>
            <td><?= $user['name'] ?></td>
            <td><?= $user['email'] ?></td>
            <td>
                <!-- Add links for edit and delete actions -->
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    

Create User View

  1. Create a file named create_user.php in the app/Views directory.
  2. Add the following code for the form:
    <h1>Create User</h1>
    <form action="/user/store" method="post">
        <input type="text" name="name" placeholder="Name" required>
        <input type="email" name="email" placeholder="Email" required>
        <button type="submit">Submit</button>
    </form>
    

Conclusion

In this tutorial, we covered the essential steps to create a CRUD application using CodeIgniter 4 and MySQL. You have learned how to set up your environment, configure the database, create models and controllers, and build views to interact with your data.

Next steps include implementing the update and delete functionalities in the controller and adding validation to enhance user experience. Happy coding!