我在尝试插入批量数据时遇到了麻烦。
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。
感谢任何帮助。
答案 0 :(得分:0)
是的,我认为你在正确的道路上。如果值存在,您只需要检查数据库。 像这样:
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
}
}