Complete basic insert, view, edit, delete and update in Codeigniter | 2my4edge

10 December 2015

Complete basic insert, view, edit, delete and update in Codeigniter

Codeigniter is one of the popular framework in php, here we are going to learn about complete basic functionality of codeignter like insert, view, edit, delete and update. This will help all the codeignter workers. with this functionality they manage codeignter and easy learn the functionality. Let see the steps and codes one by one.

basic insert, view, edit, delete and update in Codeigniter php frame work
DOWNLOAD  SQL FILE                   LIVE DEMO

STEP 1 :
First we want to download the codeignter complete framework file form codeignter site Click to Codeignter site. Download the codeignter file as .zip format and extract the files. 

Codeigniter complete files details
Copy the above all files and create one folder in your WAMP www folder or XAMPP htdocs folder.

STEP 2 :
Then we have Open application->config->config.php file.

There you can see
$config['base_url'] = '';

There we have to give our folder site path like the below.
$config['base_url'] = 'http://localhost/blogs/codeignter/';

That above path is my current site location path.

STEP 3 :
Then we are going use database and session here, so we have to autoload that libraries here, for that
application->config->autoload.php file.

there you can see
$autoload['libraries'] = array();

there we have load the libraries. like the below. here we are going to use database and session.
$autoload['libraries'] = array('database','session');

STEP 4 :
Database setting goes in application->config->database.php
There you have config your database details.

STEP 5 :
Codeignter framework is MVC framework, its strats in function from controller then if model is the model then view. So First we are going to Set Controller. While we are downloading codeigniter already one Welcome.php file will be there in the controller folder.

STEP 6 :
DEFAULT DOWNLOADED CONTROLLER Welcome.php file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        $this->load->view('welcome_message');
    }
}

AFTER ALL FUNCTIONS ADDED Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');                    /***** LOADING HELPER TO AVOID PHP ERROR ****/
        $this->load->model('Welcome_model','welcome'); /* LOADING MODEL * Welcome_model as welcome */
    }


    /**************************  START FETCH OR VIEW FORM DATA ***************/
    public function index()
    {
        $this->data['view_data']= $this->welcome->view_data();
        $this->load->view('welcome_message', $this->data, FALSE);
    }
    /****************************  END FETCH OR VIEW FORM DATA ***************/


    /****************************  START OPEN ADD FORM FILE ******************/
    public function add_data()
    {
        $this->load->view('add');
    }
    /****************************  END OPEN ADD FORM FILE ********************/

    
    /****************************  START INSERT FORM DATA ********************/
    public function submit_data()
    {
    $data = array('username'                   => $this->input->post('username'),
                  'email'                      => $this->input->post('email'),
                  'sex'                        => $this->input->post('sex'),
                  'address'                    => $this->input->post('address'),
                  'created_date'               => date("m/d/y h:i:s"),
                  'status'                     => 'Y');
    
    $insert = $this->welcome->insert_data($data);
    $this->session->set_flashdata('message', 'Your data inserted Successfully..');
    redirect('welcome/index');
    }
    /****************************  END INSERT FORM DATA ************************/


    /****************************  START FETCH OR VIEW FORM DATA ***************/
    public function view_data()
    {
    $this->data['view_data']= $this->welcome->view_data();
    $this->load->view('welcome_message', $this->data, FALSE);
    }
    /****************************  END FETCH OR VIEW FORM DATA ***************/

    
    /****************************  START OPEN EDIT FORM WITH DATA *************/
    public function edit_data($id)
    {
    $this->data['edit_data']= $this->welcome->edit_data($id);
    $this->load->view('edit', $this->data, FALSE);
    }
    /****************************  END OPEN EDIT FORM WITH DATA ***************/


    /****************************  START UPDATE DATA *************************/
    public function update_data($id)
    {
    $data = array('username'                   => $this->input->post('username'),
                  'email'                      => $this->input->post('email'),
                  'sex'                        => $this->input->post('sex'),
                  'address'                    => $this->input->post('address'),
                  'created_date'               => date("m/d/y h:i:s"),
                  'status'                     => 'Y');
    $this->db->where('id', $id);
    $this->db->update('user_data', $data);
    $this->session->set_flashdata('message', 'Your data updated Successfully..');
    redirect('welcome/index');
    }
    /****************************  END UPDATE DATA ****************************/


    /****************************  START DELETE DATA **************************/
    public function delete_data($id)
    {  
    $this->db->where('id', $id);
    $this->db->delete('user_data');
    $this->session->set_flashdata('message', 'Your data deleted Successfully..');
    redirect('welcome/index');
    }
    /****************************  END DELETE DATA ***************************/

}

STEP 7 :
Then MODEL folder. While downloading codeinginter, there only model folder will be there. There we have add .php file. Here i have created Welcome_model.php file, That file only we have loaded in controller. Here only we are going to write all kind of mysql or msqli queries.
Here in our File.
<?php
class Welcome_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

   /**************************  START INSERT QUERY ***************/
    public function insert_data($data){
        $this->db->insert('user_data', $data); 
        return TRUE;
    }
    /**************************  END INSERT QUERY ****************/

    
    /*************  START SELECT or VIEW ALL QUERY ***************/
    public function view_data(){
        $query=$this->db->query("SELECT ud.*
                                 FROM user_data ud 
                                 WHERE ud.status = 'Y'
                                 ORDER BY ud.id ASC");
        return $query->result_array();
    }
    /***************  END SELECT or VIEW ALL QUERY ***************/

    
    /*************  START EDIT PARTICULER DATA QUERY *************/
    public function edit_data($id){
        $query=$this->db->query("SELECT ud.*
                                 FROM user_data ud 
                                 WHERE ud.id = $id");
        return $query->result_array();
    }
    /*************  END EDIT PARTICULER DATA QUERY ***************/

}

STEP 8 :
ADD FORM add.php, this is the form, this will load by the Welcome controller function add_data()
There only we are loading this page to view
<div id="container" class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h2 class="text-center">Insert Add data Form in codeignter sample </h2>
            <br><br>
          <form method="post" action="<?php echo site_url('Welcome/submit_data'); ?>" name="data_register">
            <label for="Name">Enter you name</label>
              <input type="text" class="form-control" name="username" required >
            <br>
            <label for="Email">Enter you Email</label>
              <input type="email" class="form-control" name="email" required>
            <br>
            <label for="Sex">Select Sex</label><br>
              <input type="radio" name="sex" checked value="Male" required > Male &nbsp;  
              <input required type="radio" name="sex" value="Female" > Female
            <br><br>
            <label for="Email">Address</label>
              <textarea name="address" class="form-control" rows="6" required ></textarea>
            <br><br>
              <button type="submit" class="btn btn-primary pull-right">Submit</button>
            <br><br>
          </form>
        </div>
    </div>
</div>


STEP 9 :
This is to load all the data what are all we are entered. this also comes under the Welcome controller with the function name view_data()
there that goes to Welcome_model, there view_data function() to perform the query and the that will display the data in welcome_message.php file.
<div id="container" class="container" >

<!--******************** START SESSION SETFLASH MESSAGES *****************************-->
       <?php if($this->session->flashdata('message')){?>
          <div class="alert alert-success">      
            <?php echo $this->session->flashdata('message')?>
          </div>
        <?php } ?>
<!--************************* END SESSION SETFLASH MESSAGES   ************************-->


        <br>
        <div align="center"> 
          <a href="<?php echo site_url('Welcome/add_data'); ?>">Click to add new Record</a>
        </div>
        <br>


<!--*************************  START  DISPLAY ALL THE RECODEDS *************************-->
        <table class="table table-bordered table-hover table-striped" >
            <thead>
            <tr>
                <th>No.</th>
                <th>User name</th>
                <th>Email</th>
                <th>Sex</th>
                <th>Address</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
            </thead>

            <tbody>
              <?php
                if(isset($view_data) && is_array($view_data) && count($view_data)): $i=1;
                foreach ($view_data as $key => $data) { 
                ?>
                <tr <?php if($i%2==0){echo 'class="even"';}else{echo'class="odd"';}?>>
                    <td><?php echo $i; ?></td>
                    <td><?php echo $data['username']; ?></td>            
                    <td><?php echo $data['email']; ?></td>
                    <td><?php echo $data['sex']; ?></td>
                    <td><?php echo $data['address']; ?></td>
                    <td><a href="<?php echo site_url('Welcome/edit_data/'. $data['id'].''); ?>">Edit</a></td>            
                    <td><a href="<?php echo site_url('Welcome/delete_data/'. $data['id'].''); ?>">Delete</a></td>
                </tr>
                <?php
                    $i++;
                      }
                    else:
                ?>
                <tr>
                    <td colspan="7" align="center" >No Records Found..</td>
                </tr>
                <?php
                    endif;
                ?>

            </tbody>                                
        </table>
<!--*********************  END  DISPLAY ALL THE RECODEDS ******************************-->
</div>


STEP 10 :
EDIT and UPDATE FORM edit.php file
This Edit form same like add.php file. but here this will come with value. that we have to update data.
It is coming from the controller Welcome, function edit_data($id). that will go the Welcome_model function edit_data($id). that edit.php file will be like
<div id="container" class="container">

<div class="row">
 <div class="col-md-8 col-md-offset-2">
        <h2 class="text-center">Edit data Form in codeignter sample </h2>
        <br><br>
    <?php
      if(isset($view_data) && is_array($view_data) && count($view_data)): $i=1;
      foreach ($edit_data as $key => $data) { 
    ?>
    <form method="post" action="<?php echo site_url('Welcome/update_data/'.$data['id'].''); ?>" name="data_register">
        <label for="Name">Enter you name</label>
        <input type="text" class="form-control" name="username" value="<?php echo $data['username']; ?>" required >
        <br>
        <label for="Email">Enter you Email</label>
        <input type="email" class="form-control" name="email" value="<?php echo $data['email']; ?>" required>
        <br>
        <label for="Sex">Select Sex</label><br>
        <input type="radio" name="sex" <?php if($data['sex'] == 'Male' ) { echo 'checked'; } ?> value="Male" required > Male 
        &nbsp;  <input required type="radio" name="sex" <?php if($data['sex'] == 'Female' ) { echo 'checked'; } ?> value="Female" > Female
        <br><br>
        <label for="Email">Address</label>
        <textarea name="address" class="form-control" rows="6" required ><?php echo $data['address']; ?></textarea>
        <br><br>
        <button type="submit" class="btn btn-primary pull-right">Submit</button>
        <br><br>
    </form>
     <?php
        }endif;
     ?>
    <br><br>
 </div>
</div>
  
</div>

After Submitting this form it will performing in the action path, ie update_data() in Controller. that i made update function without going model.

I hope this post is really helpful to all codeigniter fresher and beginners.

For more Tutorial like this. Keep in touch with me.. Thanks for visiting. if you have any Queries. Please feel free to comment below.







RELATED POSTS :

57 comments:

  1. Can you write about the database structure? All I know is that there should be a table called user_data with a column called status.

    ReplyDelete
  2. Worked backwards. I think this is the code for the database.

    CREATE TABLE IF NOT EXISTS `user_data` (
    `id` tinyint(4) NOT NULL AUTO_INCREMENT,
    `username` varchar(100) NOT NULL,
    `email` varchar(100) NOT NULL,
    `sex` varchar(100) NOT NULL,
    `address` varchar(100) NOT NULL,
    `created_date` varchar(100) NOT NULL,
    `status` varchar(100) NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

    ReplyDelete
    Replies
    1. CREATE TABLE IF NOT EXISTS `user_data` ( 30 `id` int(11) NOT NULL, 31 `username` varchar(250) NOT NULL, 32 `email` varchar(250) NOT NULL, 33 `sex` varchar(150) NOT NULL, 34 `address` varchar(250) NOT NULL, 35 `created_date` datetime NOT NULL, 36 `status` enum('Y','N') NOT NULL DEFAULT 'Y' 37 ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

      Delete
  3. i m getting some error in edit data ..i tried all the way but its not getting fixed.. kindly help

    ReplyDelete
    Replies
    1. The edit functionality is not working. The author has used the same php code to view the records -

      $data) {
      ?>

      Delete
    2. use this code in edit.php

      Delete
    3. if(isset($edit_data) && is_array($edit_data) && count($edit_data)): $i=1;
      foreach ($edit_data as $key => $data) {
      ?>
      before form tag

      Delete
    4. use $edit_data instead of $view_data

      Delete
    5. Change this code to given correct code in edit.php,
      old code:
      $data) {
      ?>
      as correct code:
      $data) {
      ?>
      After this change its works.

      Delete
    6. edit.php don't work how to work

      Delete
  4. error : Undefined property: Welcome::$welcome_model

    ReplyDelete
  5. how to run this program please explain me .

    ReplyDelete
  6. done a very good explain

    ReplyDelete
  7. please am not able to add a data this is the error I am seeing

    Object not found!

    The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

    If you think this is a server error, please contact the webmaster.

    Error 404

    localhost
    Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.6

    ReplyDelete
  8. A PHP Error was encountered

    Severity: Notice

    Message: Undefined variable: user_id

    Filename: views/home.php

    Line Number: 124

    Backtrace:

    File: C:\wamp\www\psis\application\views\home.php
    Line: 124
    Function: _error_handler

    File: C:\wamp\www\psis\application\controllers\Home.php
    Line: 13
    Function: view

    File: C:\wamp\www\psis\index.php
    Line: 315
    Function: require_once

    ReplyDelete
  9. Thank You It's working perfectly

    ReplyDelete
  10. Thank You It's working perfectly

    ReplyDelete
  11. after click edit button URL show only title
    dont show data to edit

    ReplyDelete
    Replies
    1. In edit.php file u have to remove following Condition
      >> if(isset($view_data) && is_array($view_data) && count($view_data)): $i=1;
      and also remove end if at last of page and then check it's working

      Delete
  12. only show
    Edit data Form in codeignter sample
    after click edit link.

    ReplyDelete
  13. OK. i am read correct recommand above comment
    i can solve edit.php to show data to edit

    thank you very much. again

    ReplyDelete
  14. edit.php not working data is not updating

    ReplyDelete
    Replies
    1. if(isset($edit_data) && is_array($edit_data) && count($edit_data)): $i=1;
      foreach ($edit_data as $key => $data) {
      ?>

      before form tag

      Delete
  15. use $edit_data instead of $view_data
    now edit.php is working

    ReplyDelete
  16. Error:

    Fatal error: Cannot redeclare Welcome::index() in C:\xampp\htdocs\CodeIgniter\application\controllers\Welcome.php on line 33

    ReplyDelete
  17. I have uplaoding the pdf file using php this is not not working

    $allowedExts = array("pdf", "doc");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if (($_FILES["file"]["type"] == "application/pdf")
    || ($_FILES["file"]["type"] == "application/doc")
    && ($_FILES["file"]["size"] < 200000)
    && in_array($extension, $allowedExts))
    {
    if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "
    ";
    }
    else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "
    ";
    echo "Type: " . $_FILES["file"]["type"] . "
    ";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB
    ";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
    ";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
    {
    echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {
    move_uploaded_file($_FILES["file"]["tmp_name"],
    "upload/" . $_FILES["file"]["name"]);
    echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
    }
    }
    else
    {
    echo "Invalid file";
    }

    anyone upload the pdf file please share your code

    ReplyDelete
  18. Where should I put the add.php and the rest of the files which specific folder

    ReplyDelete
    Replies
    1. add.php and edit.php in application->view folder. Click Download to download files and check the demo.

      @ABDUL WAHAB

      Delete
    2. I meant step 7 up to ten those files without php only div tags

      Delete
    3. I also need help like I want my application to register a student and register a course with name and code ,they should be in different db tables but be view in the same table

      Delete
  19. when i add the data...some error are occurs...
    Field 'id' doesn't have a default value
    Filename: D:/wamp64/www/codeignter/application/models/Welcome_model.php

    Line Number: 11

    ReplyDelete
  20. Can you do this also with PhpMyAdmin MYSQL ?

    ReplyDelete
  21. edit .php is not working yaar

    ReplyDelete
  22. A PHP Error was encountered

    Severity: Parsing Error

    Message: syntax error, unexpected '->' (T_OBJECT_OPERATOR)

    on controller

    public function index()
    {
    $this->data['view_data']= $this->booking.stations->view_data();
    $this->load->view('booking_stations_view', $this->data, FALSE);
    }

    Help please!

    ReplyDelete
  23. edit .php is not working. Check SQL Syntax on how to UPDATE and SET from variables to the table

    ReplyDelete
  24. i can't able to submit a form

    ReplyDelete
  25. http://localhost/project/codeigniter/index.php/AddController/submit_data

    404 error found

    ReplyDelete
  26. This is good. i have learning basic so very helpful

    ReplyDelete
  27. when i go to this link,opened blank page why plz help me out,its urgent.
    Click to add new Record

    ReplyDelete
  28. what is the step 9's file name?

    ReplyDelete
  29. Thanks for this great sharing

    ReplyDelete
  30. when i Click to add new Record they show
    index.php/Welcome/add_data
    page not found
    can any help me please

    ReplyDelete
  31. when i click edit it could not open edit form

    ReplyDelete
  32. where is css file

    ReplyDelete
  33. The PDF standard grants individuals in various areas to take a shot at similar reports. https://www.altoprotectpdf.com/

    ReplyDelete
  34. Hello i would like to ask directive about "delete" because it's not worked

    ReplyDelete

^