1
votes

I'm working on a project (using codeigniter) where I use a lot of Active record .

The problem i'm facing is the following :

I receive an array of data and i have to fill few tables by using :

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

Now sometime $data contains elements not available inside the table so instead i have to do something like :

unset($data['action']);
unset($data['date']);

Before inserting or I just build another array that contains the exact same element of a specific table .

$arr = array( 'x' => $data['x'])

I already used Kohana before and i know when you insert using the ORM it just ignores elements not available in a specific table .

Is there something like that in Codeigniter ?

PS) Without using any external library

2

2 Answers

1
votes

CI ActiveRecord is not an ORM. If you want to use an ORM with codeignter, your only option is to use a third-party library: http://datamapper.wanwizard.eu/

You can always loop through the array before sending it to the db and unset data that doesn't contain anything (if in fact the delineator is an empty element):

foreach($data as $k => $v){
    if($v == ''){
        unset($data[$k]);
    }
}

Otherwise, you could create switch spaghetti to unset the elements based on the db and the page sending the data:

switch ($page){
    case "page1":
        unset($data['blah']);
    break;
    ....
}
1
votes

As far as I'm aware the built-in feature like that doesn't exist in CI's Active Record (by the way, it is not an ORM).

If unsetting the array elements manually is too much of a hassle, the auto proccess would look like:

function my_insert ($table, $data) {
    $query = $this->db->query('SHOW columns FROM '.$table);
    $columns = array();
    foreach ($query->result_array() as $row) {
        $columns[] = $row['Field'];
    }

    foreach ($data AS $key => $value) {
        if (!in_array($key, $columns)) {
            unset($data[$key]);
        }
    }

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

It's not tested and some other checks may be needed, but that should help you to take off.