Miscellaneous Code

  Home arrow Miscellaneous Code arrow Page 4 - Deleting Database Records with the Cod...
MISCELLANEOUS CODE

Deleting Database Records with the CodeIgniter PHP Framework
By: Alejandros Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 3
    2009-09-09

    Table of Contents:
  • Deleting Database Records with the CodeIgniter PHP Framework
  • Review: selects, inserts and deletes with the previous generic model
  • A new method for deleting database rows
  • The enhance version of the AbstractModel class

  •  
     

    SEARCH CODEWALKERS

    TOOLS YOU CAN USE

    advertisement

    Deleting Database Records with the CodeIgniter PHP Framework - The enhance version of the AbstractModel class


    (Page 4 of 4 )

    As I expressed in the previous section, it’s necessary to list the complete source code that corresponds to the “AbstractModel” class, this time including the definition of the “delete()” method that you learned before. So, here’s how this class looks after incorporating the new method:

    abstract class MY_Model extends Model

    {

    protected $table = ''; // table associated to the model

    protected $fields = array(); // fields of table associated to the model

    protected $id = NULL; // value of the primary key of the table associated to the model

    protected $data = array(); // model input data

    protected $insertID = NULL; // insertion ID

    protected $numRows = NULL; // number of rows returned by SELECTS

    protected $validation = array(); // model validation rules

    protected $errors = array(); // model errors

     

    /**

    * Constructor

    *

    * @access protected

    */

    protected function __construct()

    {

    parent::Model();

    // get CI super object as a model property

    $this->ci =& get_instance();

    }

     

    /**

    * Sets associated table data for the model

    *

    * @author Alejandro Gervasio

    * @return void

    * @access public

    */

    public function setTableData($table = 'default')

    {

    if ($this->db->table_exists($table))

    {

    $this->table = $table;

    $this->fields = $this->db->field_names($this->table);

    }

    }

     

    /**

    * Sets value of primary key of the associated table for the model

    *

    * @author Alejandro Gervasio

    * @param integer

    * @return void

    * @access public

    */

    public function setID($id)

    {

    $this->id = is_integer($id) AND $id > 0 ? $id : 1;

    }

     

    /**

    * Gets value of primary key of the associated table for the model

    *

    * @author Alejandro Gervasio

    * @return integer

    * @access public

    */

    public function getID()

    {

    return $this->id;

    }

     

    /** Sets input data for the model

    *

    * @author Alejandro Gervasio

    * @param array

    * @return void

    * @access public

    */

    public function setData($data)

    {

    if ( is_array($data) AND count($data) > 0)

    {

    foreach ($data as $key => $value)

    {

    if (array_search($key, $this->fields) === FALSE)

    {

    unset($data[$key]);

    }

    }

    $this->data = $data;

    }

    }

     

    /**

    * Sets validation rules for model data

    *

    * @author Alejandro Gervasio

    * @param array

    * @return void

    * @access public

    */

    public function setValidation($validation)

    {

    if ( is_array($validation) AND count($validation) > 0)

    {

    foreach ($validation as $field => $rule)

    {

    if (array_search($field, $this->fields) === FALSE)

    {

    unset($validation[$key]);

    }

    }

    $this->validation = $validation;

    }

    }

     

    /**

    * Returns a result set with specified fields according to given conditions.

    *

    * @author Alejandro Gervasio

    * @return query result on success - Boolean FALSE on failure

    * @access public

    */

    public function fetch($fields = '*', $where = NULL, $order = 'id ASC', $limit = NULL, $offset = 0, $join = NULL)

    {

    if ($fields != '*')

    {

    $this->db->select($fields);

    }

    if ($this->id != NULL)

    {

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

    }

    elseif($where != NULL)

    {

    $this->db->where($where);

    }

    if ($order != 'id ASC')

    {

    $this->db->orderby($order);

    }

    if ($limit != NULL)

    {

    $this->db->limit($limit, $offset);

    }

    if( $join != NULL)

    {

    $this->db->join($join);

    }

    $query = $this->db->get($this->table);

    $this->numRows = $query->num_rows();

    if ($this->numRows > 0)

    {

    return ($this->numRows > 1 ) ? $query->result() : $query->row();

    }

    $this->errors[] ='No rows were returned by the query.';

    return FALSE;

    }

     

     

    /** Saves model data into associated table (validation rules are applied to input data)

    *

    *

    * @author Alejandro Gervasio

    * @return integer on success - Boolean FALSE on failure

    * @access public

    */

     

    public function save()

    {

    if ($this->data == NULL)

    {

    $this->errors[] = 'Error saving row.';

    return FALSE;

    }

    // validate input data

    if( !$this->validate())

    {

    return FALSE;

    }

    // Insert new row if ID was not set in the model

    if ($this->id == NULL)

    {

    $this->db->insert($this->table, $this->data);

    $this->insertID = $this->db->insert_id();

    return $this->insertID;

    }

    // Otherwise update existing row

    else

    {

    $this->db->where('id', $this->id)->update($this->table, $this->data);

    return $this->db->affectedRows;

    }

    }

    /** Deletes model data from associated table (validation rules are applied to input data)

    *

    *

    * @author Alejandro Gervasio

    * @return Boolean TRUE on success - Boolean FALSE on failure

    * @access public

    */

    public function delete()

    {

    if ($this->id == NULL)

    {

    $this->errors[] = 'Error deleting row.';

    return FALSE;

    }

    $this->db->where('id', $this->id)->delete($this->table);

    return TRUE;

    }

    }

    There you have it. At this point, the generic model looks much more functional, since it’s capable of performing CRUD operations against its associated database table. That’s very, very exciting. But wait a minute! As you may have noticed, the “save()” method calls internally a private method called “validate(),” which should be responsible for checking the validity of input data before proceeding to perform an insert or an update operation.

    As you probably guessed, I’m going to show you how this method will be implemented in the upcoming tutorial. In the meantime, feel free to tweak the class’s source code and have fun by introducing your own improvements.

    Final thoughts

    In this fifth chapter of the series, I demonstrated how to add a brand new method to the generic model class, which is tasked with deleting rows from the specified database table. However, I must say that the signature of the model is still far from complete, since it’s necessary to implement the validate()” method, which is called internally within the “save()” function.

    In the forthcoming article, I’m going to create such a method, in this way providing the generic model with the capability to validate incoming data. So, want to see how this will be done? Then don’t miss the next part!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.
    blog comments powered by Disqus

    MISCELLANEOUS CODE ARTICLES

    - Creating a Web Page Controller with the HMVC...
    - Coding Controllers and Views for the HMVC De...
    - A Sample Web Application with the HMVC Desig...
    - Adding a Class to Parse Views to an HMVC Des...
    - Building a Model Class for the HMVC Design P...
    - Filtering Input Data and Generating HTML For...
    - The HMVC Design Pattern: Working with MySQL ...
    - Dispatching Requests to MVC Triads with the ...
    - Implementing the Hierarchical Model-View-Con...
    - A Web App Based on a Model for the CodeIgnit...
    - Completing a Model for the CodeIgniter PHP F...
    - Validating Input Data with the CodeIgniter P...
    - Deleting Database Records with the CodeIgnit...
    - Inserting Database Records with a CodeIgnite...
    - Fetching Database Rows with a Model for the ...


    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap