1

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.

3
  • Your example code isn't very clear to me, but anyway the 'columnName' should be used as a key & the value is the value of that key so it should look something like this $Products = array( array('id' => 1, 'name' => 'Something' ), array('id' => 2, 'name' => 'AnotherProduct')); Commented Aug 23, 2013 at 20:56
  • You may use print_r or var_dump to make sure you data looks OK before throwing it at ->insert_batch Commented Aug 23, 2013 at 20:57
  • thanks for feedback so the problem is the following the keys are in a separate array $into Commented Aug 23, 2013 at 21:03

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.