Retrieve, Insert, Update and Delete Functionality in Codeigniter – Info PHP
Introduction
CodeIgniter is an Application Development Framework; a toolkit. It has a small performance footprint due to the modular approach to loading its libraries and does a great job of separating logic from presentation using a Model-View-Controller (MVC) dynamic. CodeIgniter allows information to be retrieved, inserted, updated and deleted in your database with minimal scripting. In some cases only one or two lines of code is necessary to perform a database action.
Requirements
- PHP Knowledge
- PHP 5.3+ (5.4 Preferred)
- MySQL
- Apache (enabled mod_rewrite)
- Or one of these setup: WAMP / XXAMP / MAMP / or LAM
When you need CodeIgniter
Retrieved Record
If you are using Codeigniter you can use SQL SELECT statements.
- $this->db-get();
- $query = $this->db->get(‘database-table-name’);
- The second and third parameters enable you to set a limit and offset clause:
- $query = $this->db->get(‘database-table-name, 10, 20);
- $query = $this->db->get(database-table-name);
- foreach ($query->result() as $row)
- {
- echo $row->field1;
- echo $row->field2;
- echo $row->field3;
- echo $row->field4;
- echo $row->field5;
- }
Insert data
You can either pass an array or an object to the function. Here is an example of using an array:
- $data = array(
- ‘title’ => ‘My title’ ,
- ‘name’ => ‘My Name’ ,
- ‘date’ => ‘My date’
- );
- $this->db->insert(‘database-table-name”, $data);
Updating Data
You can pass an array or an object to the function. Here is an example of using an array:
- $data = array(
- ‘title’ => $title,
- ‘name’ => $name,
- ‘date’ => $date
- );
- $this->db->where(‘id’, $id);
- $this->db->update(‘database-table-name’, $data);
Deleting Data
- $this->db->delete();
- Generates a delete SQL string and runs the query.
- $this->db->delete(‘database-table-name’, array(‘id’ => $id));
- The first parameter is the table name, the second is the where clause. You can also use the where() or or_where() functions instead of passing the data to the second parameter of the function:
- $this->db->where(‘id’, $id);
- $this->db->delete(‘database-table-name’);
- An array of table names can be passed into delete() if you would like to delete data from more than 1 table.
- $tables = array(‘table1’, ‘table2’, ‘table3’);
- $this->db->where(‘id’, ‘5’);
- $this->db->delete($tables);
Article Prepared by Ollala Corp