【问题标题】:Codeigniter batch insert queryCodeigniter 批量插入查询
【发布时间】:2013-08-23 19:43:37
【问题描述】:

我尝试使用 codeigniter 在我的 MySQL 表中插入数据。

首先,我从配置 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 数组包含目标列,我不知道如何在我的产品数组中推送主题。

【问题讨论】:

  • 您的示例代码对我来说不是很清楚,但无论如何,“columnName”应该用作键,值是该键的值,所以它应该看起来像这样 $Products =数组(数组('id' => 1, 'name' => 'Something'), array('id' => 2, 'name' => 'AnotherProduct'));
  • 您可以使用 print_r 或 var_dump 来确保您的数据看起来不错,然后再将其扔到 ->insert_batch
  • 感谢反馈,所以问题是以下键位于单独的数组 $into

标签: mysql codeigniter insert


【解决方案1】:

我没有正确理解您的示例代码,但这是我的尝试。

你想要这个代码

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

【讨论】:

  • 不客气,如果这对您有用,请将答案标记为“已接受”
猜你喜欢
  • 2010-10-14
  • 2012-01-28
  • 2015-10-22
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多