CodeIgniter CRUD Operations
        CodeIgniter is a popular PHP framework that is known for its simplicity and ease of use. It enables developers to create web applications rapidly and efficiently. However, many developers struggle with CRUD (Create, Read, Update, Delete) operations in CodeIgniter when working with MySQL databases. In this article, we will provide a comprehensive guide on how to perform CRUD operations in CodeIgniter using MySQL.

Contents

  • Download Codeigniter 3
  • Extract the files
  • Create a new Database
  • Create a new table
  • Create a new project folder
  • Load Libraries
  • Load helpers
  • Create a new controller file
  • Create a new model file
  • Create a new view file
  • Insert data into the database
  • Display data into database
  • Update data into database
  • Delete data into database

Download CodeIgniter

    The first step in setting up CodeIgniter is to download it from the official website. You can download the latest version of CodeIgniter 3 from the following URL:

https://codeigniter.com/userguide3/installation/downloads.html

Extract the Files

Once you have downloaded CodeIgniter 3, you need to extract the files to your local machine in a particular folder

Following these steps:

  • Create a new table in Mysql database
  • Database name is sample
  • Project folder name is codeigniter 
  • Set Base URL and Autoload Libraries and Helpers
  • Create new controller file in Path: codeigniter\application\controllers\Home.php
  • Create new model file in Path: codeigniter\application\models\Home_model.php
  • Create new view file in Path: codeigniter\application\views

For creating table the SQL query is:

CREATE TABLE crud (      
  `id` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
  `first_name` varchar(30) NOT NULL,
  `last_name` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL,
  `mobile` varchar(30) NOT NULL
);


        After successfully creating database and table, we need to do the database configuration in our CodeIgniter 3 application, so open the database.php file and add your database credentials.

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'sample',
    '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
);

 

Set Base URL and Autoload Libraries and Helpers

In this step, we need to configure the base URL and autoload libraries and helpers in our CodeIgniter 3 application, so open these files and paste the following code
  1. Open the "application/config/config.php" file in your  project
$config['base_url'] = 'http://localhost/codeigniter/';

To autoload a library in CodeIgniter 3, you need to follow these steps:

  1. Open the "application/config/autoload.php" file in your CodeIgniter 3 project.
  2. Find the line that reads "$autoload['libraries'] = array();" and add the name of the library you want to autoload inside the array.
$autoload['libraries'] = array('database');

 To autoload a helper in CodeIgniter 3, you need to follow these steps:

  1. Open the "application/config/autoload.php" file in your CodeIgniter 3 project.
  2. Find the line that reads "$autoload['helper'] = array();" and add the name of the helper you want to autoload inside the array.
$autoload['helper'] = array('url');

CodeIgniter CRUD Operations

  • Inserting Data to MySQL Database with CodeIgniter
  • Displaying Data to MySQL Database with CodeIgniter
  • Updating Data to MySQL Database with CodeIgniter
  • Deleting Data to MySQL Database with CodeIgniter

Create new controller

    Next, create new controller file in this path application/controllers/Home.php . Then open the controller file that will display the data and add the following code

<?php

class Home extends CI_Controller
{

    public function __construct()
    {
        /*call CodeIgniter's default Constructor*/

        parent::__construct();

        /*load database libray manually*/

        $this->load->database();

        /*load Model*/

        $this->load->model('Home_model');

    }

    /*Insert*/

    public function savedata()
    {

        /*load registration view form*/

        $this->load->view('save');

        /*Check submit button */

        if ($this->input->post('save')) {

            $data['first_name'] = $this->input->post('first_name');


            $data['last_name'] = $this->input->post('last_name');


            $data['email'] = $this->input->post('email');


            $data['mobile'] = $this->input->post('mobile');


            $response = $this->Home_model->saverecords($data);

            if ($response == true) {

                echo "Records Saved Successfully";
                redirect(base_url() . 'index.php/home/savedata');
            } else {

                echo "Insert error !";

            }

        }

    }

    /*Display data*/
    public function list_data()
    {
        $result['data'] = $this->Home_model->display_records();
        $this->load->view('display_records', $result);
    }


    /*Update*/
    public function update_data($id)
    {

        /*Check submit button */

        if ($this->input->post('update')) {

            $data['first_name'] = $this->input->post('first_name');

            $data['last_name'] = $this->input->post('last_name');

            $data['email'] = $this->input->post('email');

            $data['mobile'] = $this->input->post('mobile');

            $this->Home_model->update_data($id, $data);

            echo "Update successfully";
            redirect(base_url() . 'index.php/home/list_data');
        }


        /*load view form*/

        $result['data'] = $this->Home_model->display_ById($id);

        $this->load->view('update_data', $result);

    }


   public function deletedata()
    {
     
          $id = $this->input->get('id');

          $response = $this->Home_model->deleterecords($id);

          if ($response == true)
          {

            echo "Data deleted successfully !";
            redirect(base_url() . 'index.php/home/list_data');
          } else {
           
            echo "Error !";
     
     }

}

?>

Create new view

    Next, create a new view file in this path "application/views/save.php" . Then open the view file that will display the data and add the following code


<!DOCTYPE html>

<html>

<head>

    <title>Registration form</title>

</head>



<body>

    <form method="post" action="<?= base_url() ?>index.php/home/savedata">

        <table width="600" border="1" cellspacing="5" cellpadding="5">

            <tr>

                <td width="230">First Name </td>

                <td width="329"><input type="text" name="first_name" /></td>

            </tr>

            <tr>

                <td>Last Name </td>

                <td><input type="text" name="last_name" /></td>

            </tr>

            <tr>

                <td>Email ID </td>

                <td><input type="email" name="email" /></td>

            </tr>

            <tr>

                <td>Mobile</td>

                <td><input type="number" name="mobile" /></td>

            </tr>

            <tr>

                <td colspan="2" align="center"><input type="submit" name="save" value="Save Data" /></td>

            </tr>

        </table>



    </form>

</body>

</html>

   

    Next, create a new view file in this path "application/views/list_data.php" . Then open the view file that will display the data and add the following code


<!DOCTYPE html>

<html>

<head>

    <title>List Data</title>

</head>

<body>

    <table width="600" border="1" cellspacing="5" cellpadding="5">

        <tr style="background:#CCC">

            <th>Sr No</th>

            <th>First_name</th>

            <th>Last_name</th>

            <th>Email Id</th>

            <th>Mobile</th>

            <th>Action</th>

        </tr>



        <?php

        $i = 1;

        foreach ($data as $row) {

            echo "<tr>";

            echo "<td>" . $i . "</td>";

            echo "<td>" . $row->first_name . "</td>";

            echo "<td>" . $row->last_name . "</td>";

            echo "<td>" . $row->email . "</td>";

            echo "<td>" . $row->mobile . "</td>";

            echo "<td><a href='http://localhost/codeIgniter/index.php/home/update_data/" . $row->id . "'>Update</a> <a href='http://localhost/codeIgniter/index.php/home/deletedata/" . $row->id . "'>Delete</a></td>";
           
            echo "</tr>";

            $i++;

        }

        ?>

    </table>

</body>
</html>

 

       Next, create a new view file in this path "application/views/update_data.php" . Then open the view file that will display the data and add the following code


<!DOCTYPE html>

<html>

<head>

    <title>Update form</title>

</head>

<body>

    <form method="post" action="<?= base_url() ?>index.php/home/update_data/<?php echo $data->id; ?>

">

        <table width="600" border="1" cellspacing="5" cellpadding="5">

            <tr>

                <td width="230">First Name </td>

                <td width="329"><input type="text" name="first_name" value="<?php echo $data->first_name; ?>" /></td>

            </tr>

            <tr>

                <td>Last Name </td>

                <td><input type="text" name="last_name" value="<?php echo $data->last_name; ?>" /></td>

            </tr>

            <tr>

                <td>Email ID </td>

                <td><input type="email" name="email" value="<?php echo $data->email; ?>" /></td>

            </tr>

            <tr>

                <td>Mobile</td>

                <td><input type="number" name="mobile" value="<?php echo $data->mobile; ?>" /></td>

            </tr>

            <tr>

                <td colspan="2" align="center"><input type="submit" name="update" value="Update Data" /></td>

            </tr>

        </table>

    </form>

</body>

</html>


Create new model

    Next, create a new model file in this path "application/models/Home_model.php". Then open the model file that will display the data and add the following code

<?php class Home_model extends CI_Model
{
    public function __construct() {
    parent::__construct();
    }
    
  public function saverecords($data)
  {

      $this->db->insert('crud', $data);

      return true;

  }


  public function display_records()
  {

    $query = $this->db->get("crud");

    return $query->result();

  }

  public function display_ById($id)
  {

      $this->db->select("*");

      $this->db->where("id", $id);

      $query = $this->db->get("crud");

      return $query - row();

  }

  public function update_data($id, $data)
  {

      $this->db->where("id", $id);

      $this->db->update("crud", $data);

      return true;

  }

  public function deleterecords($id)
  {

    $this->db->where("id", $id);

    $this->db->delete("crud");

    return true;

  }

}


?>

 

Finally enter your project url in browser : "http://localhost/codeigniter/index.php/home/savedata"

Conclusion

    CodeIgniter 3 is a powerful feature that allows developers to manage large sets of data easily.

    We hope this guide has been helpful. If you have any questions or need further assistance, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.