I have a function that inside my class that is handled 3 pieces of data.
- filename to be parsed
- replace string which is basically the insert or replace text except for the values.
- the tablename to hold the data or delete for getting new data.
My main concern is that I can get accurate count of records new/adjusted by this function
Here is the code for just this function.
/**
* @return int|string
*
* @psalm-return 0|positive-int|string
*/
private function csvimport(string $filename,string $replace, string $tablename) {
// verify file exists
if (!file_exists($filename)) {
// return error message
return 'File not found at '.$filename;
}
// set counter
$counter = 0;
$headcount = 0;
// now read file line by line skipping line 1
$file = fopen($filename, 'r');
while (($line = fgetcsv($file)) !== FALSE) {
// check if counter is greater than zero
if ($counter > 0) {
// get number of columns in this line
$colcount = count($line);
// replace inside array?
$line = str_replace('"','',$line);
// convert array to comma-delimmited
$values = '"'.implode('","', $line).'"';
// compare colcount to headcount
while ($colcount < $headcount) {
// add comma to the end of values
$values .= ',';
// get new colcount
$colcount = count($values);
}
// create sql string
$sql = $replace.$values.',"","","","")';
// send this to do an update
$res = array();
$res = $this->sql_update($sql);
// get num rows and status
$status = $res[0];
$num_rows = $res[1];
// assemble status string
$status = $status . ' [# Of Rows '.$num_rows.']';
// do sql tracker
$this->sqltracker($sql);
$this->sqltracker($status);
} else {
// count number of columns in header
$headcount = count($line);
}
// increment counter
$counter++;
// reset colcount
$colcount = 0;
}
// close file
fclose($file);
// return
return $counter;
}