fefe
fefe

Reputation: 9055

Codeigniter batch insert query

I try to insert data in my MySQL table using codeigniter.

First I retrieve the columns from a config XML where I should insert data and the targeted nodes which should give back from another XML the insert values.

    foreach ($sql_xml as $children) {
        foreach ($children as $index => $child) {
            if ($child != 'feed_id') {
                $keys[] = $index;
                $into[] = $child; //this holds the table columns
            }
        }
    }

Then I retrieve the multiple values per row which I want to insert.

  $products = array();
        $data = array();             
        foreach ($target_xml as $feeds) {
            $feeds =  $this->xml2array($feeds); //SimpleXMLObject to array
            $columns = new RecursiveIteratorIterator(new  RecursiveArrayIterator($feeds)); //get all recursive iteration            
            foreach ($columns as $index=>$column) {   
                     if (in_array($index, $keys)) { //here I get the values on matching nodes
                        $data[] = $column;
                    }    
                } 
            $products[] = $data;// this are the datas which should be inserted
            }

Here should come the insert: I have been looking in docs which has a quite good workaround if the inserted is an associative array which in my case is created on flow on matching keys.

  $this->db->insert_batch('mytable', $products); 

The problem is that the into array which contains the target columns and I don't know how to push theme in my product array.

Upvotes: 1

Views: 2470

Answers (1)

ahmad
ahmad

Reputation: 2729

I didn't understand your example code correctly, but here's my try on it.

You want this code

if ($child != 'feed_id') {
     $keys[] = $index;
     $into[] = $child; //this holds the table columns
}

To be get changed to something like this

if ($child != 'feed_id') {
     $keys[$index] = $child;
}

And you want this one

if (in_array($index, $keys)) {
    $data[] = $column;
}

To be change like this

if ( array_key_exists($index, $keys) ) {
    $data[$keys[$index]] = $column;
}

Upvotes: 2

Related Questions