July 09, 2014

July 09, 2014
In this article, we are going to discuss about the simple trick to shorten the input form to database table in CodeIgniter (CI). I found this trick when I have to insert data that have many data fields for example I have 5 table each table have about 20 fields. In CodeIgniter (CI) we have active record class to make it easy when inserting to database.

Basic codeigniter active record is

$data = array(
   'title' => 'My title' ,
   'name' => 'My Name' ,
   'date' => 'My date'
);

$this->db->insert('mytable', $data);

Form code

In the form field name I use the same name on the input fields so I can pass the input fields as array.

<form method="post" action="">
<label>Fields 1</label>
<input type="text" name="fields[fields1]"/>
<label>Fields 2</label>
<input type="text" name="fields[fields2]"/>
<label>Fields 3</label>
<input type="text" name="fields[fields3]"/>
<!-- other field (text, select, textarea, etc) -->
<label>Fields 19</label>
<input type="text" name="fields[fields19]"/>
<label>Fields 20</label>
<input type="text" name="fields[fields20]"/>
<input type="submit" value="submit" />
</form>

Controller

In the controller code, after the form being submitted, I have used input class for fetching input data form, or you can use original $_POST variable.

$this->fields = $this->input->post('fields');

// check fields
if (strlen($this->fields['fields1']) == 0) {
$this->error['fields1'] = 'fields1 cannot be empty';
}
// other validation ....

$this->db->insert('some_table_name', $this->fields);

As you can see above when inserting data to table, when using active record insert feature, we don't have to define one by one to array data field like the original example and this might save you some time. When dealing with many form fields just make the input form name as array.

0 comments:

Post a Comment