I have a set of csv files to add to or update several tables. The csv data is a mix of old (possibly changed) records and new.
That means during the import I have to check whether that record exists - updating if it does and inserting if not. To add to the fun the unique columns are mostly guid format and are not the first in the listing.
Ultimately I want to use an array of file names and the column used in each for searching and iterate through that to automate the import.
So I have been adapting ideas found in my searches here and have succeeded in getting the insert to work but I just cannot construct an effective update instruction.
In the code I am echoing the mysql so I can see (and check via phpAdmin) what is going on. I just cannot get any content out of $settin
$con= mysql_connect("my_connection_details");
mysql_select_db('issuetest');
function csv_file_to_mysql_table($source_file, $target_table, $fieln, $max_line_length=0) {
if (($handle = fopen("$source_file", "r")) !== FALSE) {
$columns = fgetcsv($handle, $max_line_length, ",");
$key = array_search($fieln, $columns);
foreach ($columns as &$column) {
$column = str_replace(".","",$column);
}
$insert_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES";
$update_prefix = "UPDATE $target_table SET ";
while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
while (count($data)<count($columns)){
array_push($data, NULL);
}
$sql="SELECT $fieln FROM $target_table WHERE $fieln='$data[$key]'";
if(mysql_num_rows(mysql_query($sql))=='0'){
$query = "$insert_prefix (".join(",",quote_all_array($data)).");";
}else{
$settin='';
$i='0';
reset($data);
reset ($columns);
while (count($data)<count($columns)){
if($i=='0'){$settin.="$columns[$i] ='".$data[$i]."'";
}else{$settin.=",$columns[$i]='".$data[$i]."'";
}
$i++;
}
$query = "$update_prefix $settin WHERE $fieln='$data[$key]';";
}
echo $query;
}
fclose($handle);
}
}
function quote_all_array($values) {
foreach ($values as $key=>$value)
if (is_array($value))
$values[$key] = quote_all_array($value);
else
$values[$key] = quote_all($value);
return $values;
}
function quote_all($value) {
if (is_null($value))
return "NULL";
$value = "'" . mysql_real_escape_string($value) . "'";
return $value;
}
//$fiel is name of field to check
//fileN ia name of csv file
//$tabname is table to insert into
$fiel='my_field';
$tabname='my_table';
$fileN='my_csv';
$fg=csv_file_to_mysql_table($fileN,$tabname,$fiel);