【问题标题】:How do I format the data for insert_batch in Codeigniter?如何在 Codeigniter 中格式化 insert_batch 的数据?
【发布时间】:2012-02-29 19:06:42
【问题描述】:

insert_batch 有一些问题。我有如下输入:

<input type="text" name="title[]" />

在我的控制器中,我有:

for($i=0; $i<=3; $i++)
{
    $data[] = array(
        'field' => $this->input->post('text'),
        'filed2' => $this->input->post('user')
    );
}
$this->db->insert_batch('table', $data)

我做错了什么,最好的方法是什么?

【问题讨论】:

  • 您是否遇到任何错误?尝试在您的 insert_batch 语句之后立即执行 echo $this-&gt;db-&gt;last_query() 以验证插入的内容。
  • 是的,请发布错误信息。
  • 这里有什么问题?什么不工作?

标签: php database codeigniter


【解决方案1】:

如果您的字段名称包含name="text[]" 之类的括号,它将发布一个数组(您可能知道)。考虑到这一点,$this-&gt;input-&gt;post('text') 将始终返回数组本身。目前,您每次都分配完全相同的整个数组。尝试使用 $i 变量通过键访问值:

$text = $this->input->post('text');
$user = $this->input->post('user');

for($i=0; $i<=3; $i++)
{
    $data[] = array(
        'field' => $text[$i],
        'filed2' => $user[$i]
    );
}
$this->db->insert_batch('table', $data)

作为一种可能更明智的替代方法,循环遍历 $_POST 数据,选择一个字段名称:

$text = $this->input->post('text');
$user = $this->input->post('user');
foreach ($text as $key => $value)
{
    $data[] = array(
        'field' => $text[$key],
        'filed2' => $user[$key]
    );
}

这样您就不必知道期望有多少值,但这完全取决于您。

【讨论】:

  • 嗨,谢谢你的代码,它工作了一半,因为它正在发送类似...values(1,3,4t), (null null null) 你知道为什么吗?
  • 没有看到您的实际 HTML 表单和输入,我只能推测。基本上,您期望的发布数据实际上并不存在。为什么不打开错误报告并阅读错误,或者使用错误日志,或者var_dump() 或任何其他众多调试工具?
  • 好的,我有很多字段,例如 text[] title[] name[] 等,我计算它们有多少重复,我需要将 foreach 插入数据库想象一个带有重复字段的表单.. ..
  • 我已经询问了您的实际表单代码,错误信息是什么,并建议您使用基本调试。在这一点上,我看不到我的进一步帮助有用,因为它只能是猜测。如果您仍然有问题并且可以提供更多信息,请edit您的帖子,其中包含具体细节和实际代码。
【解决方案2】:

为了用户搜索“$this->db->insert_batchformatting”的利益,可能会对以下内容感兴趣。
我正在寻找一种将大量信息打包到数组中并将其作为一个操作插入到数据库表中的方法。我认为 insert_batch 可能会这样做,但它有一个我没想到的警告: 格式化数组时,每个子数组中的字段名称必须相同,即以下内容将不起作用:

 $data = array(
   array(
      'title' => 'My title' ,
      'first-name' => 'My Name' ,
      'date' => 'My date'
   ),
   array(
      'title' => 'Another title' ,
      'last-name' => 'Another Name' ,
      'date' => 'Another date'
   )
);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2017-02-13
    • 2015-01-28
    • 2014-02-07
    • 2016-09-03
    • 1970-01-01
    • 2013-07-19
    相关资源
    最近更新 更多