First Codeigniter 3 CRUD (Create,Read,Update,Delete) via Mysql

First Codeigniter Basic CRUD tutorial example. Today, we’ll show you step by step how to perform crud operation with codeigniter project using mysql database. In this tutorial, you will learn easy to insert update delete operation with codeigniter project from scratch.

In this Codeigniter first basic crud operation tutorial, You will also how to validate form data on client side without sending the form data to server. We will use jQuery plugin for validating a form data on client side.

In this article, you will learn very simple crud (create, read, update, delete) operation with codeigniter new latest version.

Table of Contents

  • Download Codeigniter Project
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credential
  • Create Controller
  • Make Model
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

You have two option for download the project using command or codeigniter website.

First way to download

In this way, You should have composer in your system. Open your command prompt and run the following command for creating a codeigniter project name “crud-app”.

composer create-project CodeIgniter/framework crud-app

After run the above command in command prompt, it will create a project with required files.

Second way to download

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter. Download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ .

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

If you want to run this project using command prompt than set the base url

$config['base_url'] = 'http://localhost:5000';

Or if you run the project with folder name

$config['base_url'] = 'http://localhost/crud_app';


Create Database With Table

In this step, we need to create database name crud_app, so let’s open your phpmyadmin and create the database with the name crud_app. After successfully create a database, you can use the below sql query for creating a table in your database.

CREATE TABLE IF NOT EXISTS notes (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
title varchar(255) COLLATE utf8_unicode_ci NOT NULL,
description text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

Setup Database Credential

Next step, we will connect the crud_app project with database, so go to application/database.php and setup the database credential here. In this file add your database name, username and password.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => 'root',
	'database' => 'crud_app',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Create Controller

Go to application/controllers/ and create a controller name Note.php. In this controller, we will create some method/function name index, add, edit, delete, update for performing a crud operation.

<?php
class Note extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('notes_model');
        $this->load->helper('url_helper');
        $this->load->helper('form');
        $this->load->library('form_validation');
    }

    public function index()
    {
        $data['notes'] = $this->notes_model->notes_list();
        $data['title'] = 'Notes List';
        $this->load->view('notes/list', $data);
    }

    public function create()
    {
        $data['title'] = 'Create Note';
        $this->load->view('notes/create', $data);
    }

    public function edit($id)
    {
        $id = $this->uri->segment(3);
        $data = array();
        if (empty($id))
        {
         show_404();
        }else{
          $data['note'] = $this->notes_model->get_notes_by_id($id);
          $this->load->view('notes/edit', $data);
        }
    }
    public function store()
    {
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('description', 'Description', 'required');
        $id = $this->input->post('id');
        if ($this->form_validation->run() === FALSE)
        {
            if(empty($id)){
              redirect( base_url('note/create') );
            }else{
             redirect( base_url('note/edit/'.$id) );
            }
        }
        else
        {
            $data['note'] = $this->notes_model->createOrUpdate();
            redirect( base_url('note') );
        }

    }


    public function delete()
    {
        $id = $this->uri->segment(3);

        if (empty($id))
        {
            show_404();
        }

        $notes = $this->notes_model->delete($id);

        redirect( base_url('note') );
    }
}

Make Model

Go to application/models/ and create model name Note_model.php.

<?php
class Notes_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }

    public function notes_list()
    {
        $query = $this->db->get('notes');
        return $query->result();
    }

    public function get_notes_by_id($id)
    {
        $query = $this->db->get_where('notes', array('id' => $id));
        return $query->row();
    }

    public function createOrUpdate()
    {
        $this->load->helper('url');
        $id = $this->input->post('id');
        $data = array(
            'title' => $this->input->post('title'),
            'description' => $this->input->post('description')
        );
        if (empty($id)) {
            return $this->db->insert('notes', $data);
        } else {
            $this->db->where('id', $id);
            return $this->db->update('notes', $data);
        }
    }

    public function delete($id)
    {
        $this->db->where('id', $id);
        return $this->db->delete('notes');
    }
}

Create Views

Go to application/views/ and create a one folder name notes, inside the notes folder we will create three views name create.php, edit.php, list.php.

First of all we need to create list.php file and put the below code inside the file.
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Codeigniter CRUD Application With Example - Tutsmake.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
    <style>
        .mt40{
            margin-top: 40px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row mt40">
   <div class="col-md-10">
    <h2>Codeigniter Basic Crud Example - Tuts Make</h2>
   </div>
   <div class="col-md-2">
    <a href="<?php echo base_url('note/create/') ?>" class="btn btn-danger">Add Note</a>
   </div>
   <br><br>
    <table class="table table-bordered">
       <thead>
          <tr>
             <th>Id</th>
             <th>Title</th>
             <th>Description</th>
             <th>Created at</th>
             <td colspan="2">Action</td>
          </tr>
       </thead>
       <tbody>
          <?php if($notes): ?>
          <?php foreach($notes as $note): ?>
          <tr>
             <td><?php echo $note->id; ?></td>
             <td><?php echo $note->title; ?></td>
             <td><?php echo $note->description; ?></td>
             <td><a href="<?php echo base_url('note/edit/'.$note->id) ?>" class="btn btn-primary">Edit</a></td>
                 <td>
                <form action="<?php echo base_url('note/delete/'.$note->id) ?>" method="post">
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
            </td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
    </table>

</div>
</div>

</body>
</html>
Next, we need to create create.php file & put the below code.
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Codeigniter CRUD Application With Example - Tutsmake.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
    <style>
        .mt40{
            margin-top: 40px;
        }
    </style>
</head>
<body>

<div class="container">

<div class="row">
    <div class="col-lg-12 mt40">
        <div class="pull-left">
            <h2>Add Note</h2>
        </div>
    </div>
</div>


<form action="<?php echo base_url('note/store') ?>" method="POST" name="edit_note">
   <input type="hidden" name="id">
     <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <strong>Title</strong>
                <input type="text" name="title" class="form-control" placeholder="Enter Title">
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <strong>Description</strong>
                <textarea class="form-control" col="4" name="description"
                 placeholder="Enter Description"></textarea>
            </div>
        </div>
        <div class="col-md-12">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>

</div>

</body>
</html>
Next, we need to create edit.php file and put the below code here.
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Codeigniter CRUD Application With Example - Tutsmake.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
    <style>
        .mt40{
            margin-top: 40px;
        }
    </style>
</head>
<body>

<div class="container">

<div class="row">
    <div class="col-lg-12 mt40">
        <div class="pull-left">
            <h2>Edit Note</h2>
        </div>
    </div>
</div>


<form action="<?php echo base_url('note/store') ?>" method="POST" name="edit_note">
   <input type="hidden" name="id" value="<?php echo $note->id ?>">
     <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <strong>Title</strong>
                <input type="text" name="title" class="form-control" value="<?php echo $note->title ?>" placeholder="Enter Title">
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <strong>Description</strong>
                <textarea class="form-control" col="4" name="description"
                 placeholder="Enter Description"><?php echo $note->description ?></textarea>
            </div>
        </div>
        <div class="col-md-12">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>

</div>

</body>
</html>

Start Development server

Open your terminal and go to inside the project folder than We will use the below command for start the development server

php -S localhost:5000

After run the above command, go to browser and hit below the url.

http://localhost:5000/

Conclusion

In this codeigniter basic crud tutorial – We have successfully created first basic crud (create, update, read, delete) project using mysql database.

You may like

  1. Codeigniter 3 Create First Ajax CRUD Application
  2. Codeigniter Send Email With Gmail Smtp Protocol
  3. Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example
  4. Laravel 6 – Ajax CRUD (Operation) Application Example
  5. Laravel 6 Angular JS CRUD Example Tutorial
  6. Upload Files/Images to Amazon s3 Cloud Using Laravel 6 Filesystem
  7. Laravel 6 CKEditor with Image Upload
  8. Ajax Image Upload in Laravel Tutorial Example From Scratch
  9. Laravel 6 Intervention Upload Image Using Ajax – Example
  10. Laravel 6 Upload Image to Database with Validation

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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