2013-08-23 95 views
1

我嘗試使用codeigniter在我的MySQL表中插入數據。Codeigniter批量插入查詢

首先,我從配置XML中檢索列,其中我應該插入數據以及應該從另一個XML返回插入值的目標節點。

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

然後我檢索我想要插入的每行多個值。

$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 
      } 

這裏應該來插入:我一直在尋找具有相當不錯的解決方法文檔如果插入的是在我的情況是在流動產生匹配鍵的關聯數組。

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

的問題是into數組,它包含了目標列,我不知道如何在我的產品陣列推主題。

+0

你的示例代碼對我來說並不是很清楚,但無論如何,'columnName'應該用作鍵,值是該鍵的值,所以它應該看起來像這樣$ Products = array(array('id '=> 1,'name'=>'Something'),array('id'=> 2,'name'=>'AnotherProduct')); – ahmad

+0

你可以使用print_r或var_dump來確保你的數據看起來沒有問題,然後把它扔在 - > insert_batch – ahmad

+0

謝謝你的反饋,所以問題是下面的鍵是在一個單獨的數組$到 – fefe

回答

2

我沒有正確理解您的示例代碼,但這裏是我的嘗試。

你要這個代碼

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

待得到改變,以這樣的

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

並且希望此類似這樣的

一個

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

要改變

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

謝謝你是我想要的快速 – fefe

+0

你歡迎,如果這對你有用,請將答案標記爲「已接受」 – ahmad