【问题标题】:Insert Data to Database Codeigniter only if item does not exit仅当项目不退出时才将数据插入数据库 Codeigniter
【发布时间】:2014-10-15 04:13:07
【问题描述】:

我在尝试插入批处理数据时遇到问题。

insert_batch 函数一切正常,但我只想插入数据库中不存在的项目,不更新它,只是忽略并插入新项目。

这是我的控制器:

csv 文件:

col0,col1,col2,col3
data1,data1,data1,data1
data2,data2,data,2,data2
data3,data3,data3,data3

插入批次:

function mres($q) {
        if(is_array($q))
            foreach($q as $k => $v)
                $q[$k] = $this->mres($v); //recursive
        elseif(is_string($q))
            $q = mysql_real_escape_string($q);
        return $q;
    }

function inserbatch(){
$csv = 'file.csv';              
                $arrResult = array();
                    $handle = fopen("uploads/csv/".$csv, "r");
                    if( $handle ) {
                    while (($row = fgetcsv($handle, 0, ",")) !== FALSE) {
                    $arrResult[] = array(
                                        'col0' => $row[0],
                                        'col1' => $row[1],
                                        'col2' => $row[2],
                                        'col3' => utf8_encode($row[3])
                                        );
                    }
                    fclose($handle);
                    }

$final = $this->mres($arrResult);

$this->model_m->addBatch($final);


}

型号:

public function addBatch($final = array()){
if($this->db->insert_batch('mytable', $final)){
                return true;
            }
        return false;
    }

数据库: id,col0,col1,col2,col3

col0 包含唯一值,如果存在于 csv 文件中需要跳过。

我的问题是如何只插入数据库中不存在的数据 col0 是唯一值,我认为需要像

如果数据来自 csv[col0] != database[col0] insert_batch。

感谢任何帮助。

【问题讨论】:

    标签: mysql codeigniter


    【解决方案1】:

    是的,我认为你在正确的道路上。如果值存在,您只需要检查您的数据库。 像这样的:

        foreach(csv[col0] as $your_data)
        {
    
        $query = $this->db->query("SELECT * FROM my_table WHERE col0 = $your_data");
        $rows = $query->num_rows();
    
          if(!$rows)
          {
           // No record has been found so here you would write the code to insert the data
          }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      相关资源
      最近更新 更多