Example 1 – a CRUD example

In this example, we will see how to use a CI model. For this example, we will use a model that performs these operations on the database: SELECT, INSERT, and UPDATE.

The example displays, all the products that are retrieved by the model productmodel at the main page in the database.

Let us assume the URI to the project root is http://mydomain.com/myproject and http://mydomain.com/myproject/product.

Note

The source code is provided with this book via URLs.

The main page has links for adding and editing a product. These links generate a form for editing and adding a product.

Let us assume the URI to the project root is http://mydomain.com/myproject and http://mydomain.com/myproject/product/add.

Suppose we want to edit and update the product with product_id 1, the link will be http://mydomain.com/myproject/product/edit/1. This example will be constructed from the following controller, model, and views:

  • application/controllers/product.php: This controller loads the model product.
    $this->load->model('productmodel'),

    This controller renders the following views:

    • productsview: This view displays all the products with links to editing and adding a product
    • productform: This view contains the form for adding and editing a product
  • application/models/productmodel.php: This model contains functions that perform these operations on the database: SELECT, INSERT, and UPDATE.
  • application/views/productsview.php: The view that displays the products.
  • application/views/productform.php: The view that contains the form.

The controller file

The controller PHP file is located at application/controllers/product.php. The controller handles the product's operations, such as adding, editing, updating, and displaying the product's table.

The controller creates a form for adding and editing a product.

For more information refer to Chapter 7, Views.

The following are the code and inline explanations:

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed'),
class Product extends CI_Controller {
// Accessory method for generating forms called by the methods add // and edit.
private function load_form($form_action, $a_values = array())
{
  // Loading the form helper
  $this->load->helper('form'),
  // Loading the form_validation library
  $this->load->library('form_validation'),
  $view_params['form']['attributes'] = array('id' => 'productform'),
  $view_params['form']['action'] = $form_action;
  $product_id = isset($a_values['product_id']) ?
  $a_values['product_id']: 0;
  $view_params['form']['hidden_fields'] = array('product_id' => $product_id);
  // product name details
  $view_params['form']['product_name']['label'] = array('text' => 'Product name:', 'for' => 'product_name'),
  $view_params['form']['product_name']['field'] = array('name' => 'product_name', 'id' => 'product_name', 'value' => isset($a_values['product_name']) ? $a_values['product_name']: '', 'maxlength' => '100', size' => '30', 'class' => 'input'),
  // product sku details
  $view_params['form']['product_sku']['label'] = array('text' => 'Product SKU:', 'for' => 'product_sku'),
  $view_params['form']['product_sku']['field'] = array('name' => 'product_sku', 'id' => 'product_sku', 'value' => isset($a_values['product_sku']) ? $a_values['product_sku']: '', 'maxlength' => '100', 'size' => '30', 'class' => 'input'),
  // product quantity details
  $view_params['form']['product_quantity']['label'] = array('text' => 'Product Quantity:', 'for' => 'product_quantity'),
  $view_params['form']['product_quantity']['field'] = array('name' => 'product_quantity', 'id' => 'product_quantity', 'value' => isset($a_values['product_quantity']) ? $a_values['product_quantity']: '', 'maxlength' => '100', 'size' => '30', 'class' => 'input'),
  // Form attributes validation rules
  $config_form_rules = array(array('field' => 'product_name', 'label' => 'Product Name','rules' => 'trim|required'), array('field' => 'product_sku', 'label' => 'Product SKU', 'rules' => 'trim|required'), array('field' => 'product_quantity', 'label' => 'Product Quantity', 'rules' => 'trim|required|integer'));
  $this->form_validation->set_rules($config_form_rules);
  return $view_params;
  }
// This controller method retrieves the products list calling the // model productmodel's method get_products() renders the results // in the view productsview.
public function index()
{
  // Loading the url helper
  $this->load->helper('url'),
  
  // Manually loading the database
  $this->load->database();
  
  // Loading the model class
  $this->load->model('productmodel'),
  
  // Calling the model productmodel's method get_products()to // retrieve the products from the database.
  $view_params['products'] = $this->productmodel->get_products();
  // Rendering the products list in the view productsview.
  $this->load->view('productsview', $view_params);
  }
// This method handles the operation of adding a product to the // database.
public function add()
{
  // Loading the url helper
  $this->load->helper('url'),
  
  // Manually loading the database
  $this->load->database();
  
  // Loading the model class
  $this->load->model('productmodel'),
  
  $a_post_values = $this->input->post();
  $view_params = $this->load_form('product/add', $a_post_values);
  
  // Validating the form
  if ($this->form_validation->run() == FALSE) {
    // Validation failed
    $this->load->view('productform', $view_params);
    } else {
    $data = $a_post_values;
    array_pop($data);
    $this->productmodel->addProduct($data);
    
    redirect('product'),
    }
  }
// This method handles the operation of editing a product
public function edit($product_id)
{
  // Loading the url helper
  $this->load->helper('url'),
  // Manually loading the database
  $this->load->database();
  
  // Loading the model class
  $this->load->model('productmodel'),
  
  $a_post_values = $this->input->post();
  // Checking if a form was submitted
  if ($a_post_values) {
    $a_form_values = $a_post_values;
    } else {
    // Get the values of the database
    $a_db_values = $this->productmodel->get_product($product_id);
    $a_form_values = array('product_id' => $a_db_values[0]->product_id, 'product_name' => $a_db_values[0]->product_name, product_sku' => $a_db_values[0]->product_sku, 'product_quantity' => $a_db_values[0]->product_quantity);
    }
  
  $view_params = $this->load_form('product/edit/' . $product_id, $a_form_values);
  // Validating the form
  if ($this->form_validation->run() == FALSE) {
    // Validation failed
    $this->load->view('productform', $view_params);
    } else {
    $a_fields = array('product_name', 'product_sku', 'product_quantity'),
    for ($index = 0; $index < count($a_fields); $index++)
    {
      $s_field = $a_fields[$index];
      $data[$s_field] = $this->input->post($s_field)
      }
    $this->productmodel->updateProduct($product_id, $data);
    redirect('product'),
    }
  }
}
/* End of file product.php */
/* Location: /application/controllers/product.php */

The model file

The model PHP file is located at application/models/productmodel.php.

In this example, the methods of the CI object db are called for generating and executing the SQL queries.

Please refer to the CI database library at http://ellislab.com/codeigniter/user-guide/database/index.html.

The following are the code and inline explanations:

<?php
class Productmodel extends CI_Model {
  // The model's constructor method
  public function __construct()
  {
    // Call the Model's parent constructor
    parent::__construct();
    }
  // This method retrieves the products list and returns an array of // objects each containing product details.
  public function get_products()
  {
    // Calling the CI's db object's method for generating SQL // queries.
    $query = $this->db->get('products'),
    // returns an array of products objects
    return $query->result();
    }
  // This method retrieves a specific product's details identified by // $product_id as a parameter
  public function get_product($product_id)
  {
    // Calling the CI's db object's methods for generating SQL // queries.
    $this->db->select('*'),
    $this->db->from('products'),
    $this->db->where('product_id', $product_id);
    
    // Calling the CI's db object method for executing the query
    $query = $this->db->get();
    // Returning array of one object element containing product // details.
    return $query->result();
    }
  
  // This method adds a product to the products table Parameters // $data - The data to insert into the table
  public function addProduct($data)
  {
    // Calling the CI's db object method for inserting a product data // into the products table.
    $this->db->insert('products', $data);
    }
  // This method updates a product row in the products table // parameters $product_id - The product id, $data - The updated // data
  public function updateProduct($product_id, $data)
  {
  // Calling the CI's db object's methods for generating SQL queries
  $this->db->where('product_id', $product_id);
  // Calling the CI's db object method for updating the product data // in the products table
  $this->db->update('products', $data);
  }
}

The view file

The view PHP file is located at application/views/productsview.php.

This view file displays a table with the products list. The following are the code and inline explanations:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Products List</title>
</head>
<body>
<table>
<tr>
  <td>ID</td>
  <td>Name</td>
  <td>SKU</td>
  <td>Quantity</td>
  <td>Actions</td>
</tr>

<?php foreach ($products as $product): ?>
<tr>
  <td><?php echo $product->product_id; ?></td>
  <td><?php echo $product->product_name; ?></td>
  <td><?php echo $product->product_sku ; ?></td>
  <td><?php echo $product->product_quantity ; ?></td>
  <td><a href="<?php echo site_url("product/edit/" . $product->product_id); ?>">Edit Product</a></td>
</tr>
<?php endforeach; ?>
</table>

<p>
  <a href="<?php echo site_url('product/add'), ?>">Add Product</a>
</p>
</body>
</html>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.109.234