【问题标题】:CodeIgniter insert_batch() [duplicate]CodeIgniter insert_batch() [重复]
【发布时间】:2015-01-28 03:31:56
【问题描述】:

好的,我想知道如何使用 insert_batch

我正在尝试这样的事情

function checkboxes($data,$category)
    {

        $insert=array(
                        'story'=>$data
                        'category'=>$category
                     );

        $this->db->insert_batch('stories_to_categories',$insert);
    }

对于 $data 我有一个数组,它可以有值和键的范围

(
    [0] => 1
    [1] => 6
    [2] => 14
    [3] => 15
    [4] => 18
)

对于类别 i 将只有一个值,例如 2

我努力在我的餐桌上取得成功

  story category
------------------------
    1        2
    6        2
    14       2
    15       2
    18       2

谁能帮帮我,我很痛苦!

【问题讨论】:

标签: php codeigniter


【解决方案1】:

您可以通过对代码稍作修改来实现这一点。 CI 文档显示,批量插入需要一个嵌入关联数组的数组:每个要插入的新行对应一个关联数组,将列映射到值。

实际上,您可能希望为您的$insert 构建一个这样的数组:

$insert=array(
    array('story'=>1, 'category'=>2).
    array('story'=>6, 'category'=>2).
    array('story'=>14, 'category'=>2).
    array('story'=>15, 'category'=>2).
    array('story'=>18, 'category'=>2).
);

由于您的类别是恒定的,您可能希望使用一个函数:

function _insert_($data, $category='2', $options=array('data'=>'story', 'category'=>'category'))
{
    $return = array();
    foreach ($data as $value)
    {
        $return[] = array($options['data']=>$value, $options['category']=>$category);
    }
    return $return;
}

然后你可以有如下的东西:

$this->db->insert_batch('stories_to_categories',_insert_($data));

希望这会有所帮助。

在下面查找参考资料:

在此处查看 CodeIgniter 参考:CodeIgniter Active Record: #Insert

编辑:Codeigniter 3.0 查询生成器类:inserting data

【讨论】:

  • 不错,看看我的解决方案
  • 函数复选框($category_checkboxes,$last_story_id) { foreach ($category_checkboxes as $box) { $insert[] = array("category" => $box, "story" => $last_story_id) ; } $this->db->insert_batch('stories_to_categories',$insert); }
【解决方案2】:
function checkboxes($category_checkboxes,$last_story_id)
    {
        foreach ($category_checkboxes as $box) 
        {
            $insert[] = array(
                              "category" => $box,
                              "story" => $last_story_id
                             );

        }

        $this->db->insert_batch('stories_to_categories',$insert);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 2014-02-07
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    相关资源
    最近更新 更多