【问题标题】:How to add INSERT IGNORE INTO in Codeigniter batch insert query如何在 Codeigniter 批量插入查询中添加 INSERT IGNORE INTO
【发布时间】:2015-10-22 22:28:48
【问题描述】:

如何使 codeigniter 函数与 insert_batch() 工作方式相同但生成类似于 INSERT IGNORE INTO 的查询?

我需要INSERT IGNORE INTO,因为我的表键之一是唯一的,并且在出现重复条目​​时显示错误。

【问题讨论】:

  • INSERT IGNORE using Codeigniter 的可能重复项
  • @Gunaseelan : 表示这个 INSERT IGNORE 会将重复的行添加到表中?
  • 不会添加重复的行。
  • 所以我需要这个,因为我不希望我的脚本在批量插入时停止,这就是我使用它的原因。你有更好的解决方案吗?
  • 我没有将此答案标记为重复。我只是标记了这个问题。我很高兴看到这个问题的解决方案

标签: php codeigniter


【解决方案1】:

我在 codeigniter 批量插入查询中搜索了添加“INSERT IGNORE INTO”而不是“INSERT INTO”的代码,但我没有找到相应的结果。 是的,我们可以使用 PHP 登录进行自定义批量插入查询,但是如果您想在 codeigniter 中执行此操作,请使用此函数。

在(codeigniter/system/database/DB_active.rec.php)中添加这个函数。

/*
*Function For Batch Insert using Ignore Into
*/
public function custom_insert_batch($table = '', $set = NULL)
{
    if ( ! is_null($set))
    {
        $this->set_insert_batch($set);
    }

    if (count($this->ar_set) == 0)
    {
        if ($this->db_debug)
        {
            //No valid data array.  Folds in cases where keys and values did not match up
            return $this->display_error('db_must_use_set');
        }
        return FALSE;
    }

    if ($table == '')
    {
        if ( ! isset($this->ar_from[0]))
        {
            if ($this->db_debug)
            {
                return $this->display_error('db_must_set_table');
            }
            return FALSE;
        }

        $table = $this->ar_from[0];
    }

    // Batch this baby
    for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100)
    {

        $sql = $this->_insert_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100));
        $sql = str_replace('INSERT INTO','INSERT IGNORE INTO',$sql);
        //echo $sql;

        $this->query($sql);
    }

    $this->_reset_write();


    return TRUE;
}

使用此功能

$this->db->custom_insert_batch($table_name, $batch_data);

谢谢!

【讨论】:

  • 不要修改系统文件夹中的文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多