CodeIgniter model database interaction
Recently I’ve been doing quite a bit of work with the PHP MVC framework, CodeIgniter. First of all – it’s great! I’ve always been a fan of object oriented programming software approaches and the CodeIgniter handles this almost perfectly. As my CodeIgniter based projects start to grow, more and more database tables are introduced which is made a lot easier with the model part of the MVC design pattern.
When it comes to CodeIgniter though I’ve found that all of my table models all have the same 2 common functions. To me it makes sense to have this functionality built into the parent ‘Model’ class within CodeIgniter but since they’re not here they are for you to add them yourself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function get($where = array(), $limit = 1000, $offset = 0) { $rows = array(); $this->db->select('*'); $this->db->where($where); $query = $this->db->get("tablename", $limit, $offset); // How many rows? if($query->num_rows() > 0) { // Loop through each row foreach($query->result() AS $row) { $rows[] = $row; } } return $rows; } function get_by_id($ID, $where = array()) { $where = array_merge(array('ID' => $ID), $where); $rows = $this->get($where, 1); return $rows[0]; } |
So what exactly are these two functions? They’re a quick and simple way for retrieving information from a database table using the relevant model within your application. By simply calling either of these functions you can quickly retrieve whatever data required and then carry on without needing to worry about table names, etc. So, if for example for whatever reason you had to rename a table you’d only need to modify it in just the one place (in the model) as opposed to having to wade through all your code if you’ve typed it manually. Sure, the likelyhood of you changing a table name is quite slim but you never know.
Of course you may want to extend this to allow for updates, deletes and inserts which only takes a few minutes. Just thought I’d put this out there in case anyone’s interested.




