【问题标题】:Php - Insert Multiple Rows in CiPhp - 在 Ci 中插入多行
【发布时间】:2018-10-30 10:05:53
【问题描述】:

我有一个数组 ['abc','xyz'];

我想一次性插入两行

我不想

loop(){
 $this->db->insert()
 }

这将运行两次插入查询

使用 CI 框架 这个数组来自用户

【问题讨论】:

  • 你使用的是什么数据库控制器?
  • @WKoppel 使用 CI 框架
  • 内循环写插入查询
  • @Daan 这是手动从数组中的输入中获取值的东西我能做什么?
  • 提问前请先阅读说明书,10秒内我在google上找到了这个:insert_batchcodeigniter.com/userguide3/database/…

标签: php codeigniter


【解决方案1】:
foreach ($this->input->post("name") as $value) {        
            $name[] = array(
                'name'=>$value,
            );
        }
$this->db->insert_batch("names",$name);

【讨论】:

  • 你想解释一下代码,以便 OP 决定为什么他需要将代码更新到这个
  • 感谢您的回答。请为您的代码示例提供一些描述。
【解决方案2】:

yourModel.php

public function urfunctionName($data)
{
  foreach($data as $res)
  {
     $this->db->insert('table_name',$res);
  }
}

希望对你有用

【讨论】:

  • 我告诉过你不要循环执行此操作
  • 告诉我你的预期结果
  • 我会得到相同的结果,但是您的代码将运行等于我的数组长度的查询,例如如果数组有 100 个索引,它将运行 100 次,这不好,我想一次插入 100 行谢谢寻求帮助 insert_batch() 做到了,谢谢大家
【解决方案3】:

您需要先构建“批量”插入查询。之后调用insert_batch 方法。

$array = ['abc','xyz'];
$batchInsertArray = buildBatchInsertArray($array);

$this->db->insert_batch('myTable', $batchInsertArray);

function buildBatchInsertArray(array $array): array
{
    $batchInsertArray = [];

     foreach ($array as $item) {
       $batchInsertArray[] = [
           'columnName' => $item
       ];
    }

    return $batchInsertArray;
}

【讨论】:

    【解决方案4】:
    $data = array(
            array(
                    'title' => 'My title',
                    'name' => 'My Name',
                    'date' => 'My date'
            ),
            array(
                    'title' => 'Another title',
                    'name' => 'Another Name',
                    'date' => 'Another date'
            )
    );
    
    $this->db->insert_batch('mytable', $data);
    
    // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')
    

    参考 :: query_builder inserting-data

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 1970-01-01
      • 2013-01-03
      • 2012-01-29
      • 2022-01-17
      • 2021-10-23
      • 1970-01-01
      • 2019-08-07
      • 2015-11-22
      相关资源
      最近更新 更多