This question already has an answer here:
I'm creating a function that imports a csv file into a database. But an error has occurred, and i was wondering how to fix this.
Error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)
My function:
importFile("ingram", "ingram_fees.txt", "ingram_fees");
function importFile($company, $fileName, $tableName) {
$filePath = "./ftp_imports/".$company."/".$fileName;
$file = fopen($filePath, "r");
$firstRowNames = fgetcsv($file);
$columnNames = array();
$rows = count($firstRowNames);
$i = 0;
while ($i < $rows) {
array_push($columnNames, toCamelCase($firstRowNames[$i]));
}
if ($result = $mysqli->query("SHOW TABLES LIKE '".$tableName."'")) {
if($result->num_rows !== 1) {
$queryCreateTable = "CREAT TABLE $tableName (";
$num = count($columnNames);
$i = 0;
while ($i < $num) {
switch (gettype($columnNames[$i])) {
case 'string':
$queryCreateTable .= $columnNames[$i] . " VARCHAR(25)";
break;
case 'integer':
$queryCreateTable .= $columnNames[$i] . " DECIMAL(10,2)";
break;
case 'double':
$queryCreateTable .= $columnNames[$i] . " DECIMAL(10,2)";
break;
case 'NULL':
$queryCreateTable .= $columnNames[$i] . " VARCHAR(25)";
break;
default:
break;
}
if ($i !== ($num - 1)) {
$queryCreateTable .= ",";
} else {
$queryCreateTable .= ");";
}
}
}
} else {//table already exists
$queryDelAll = "TRUNCATE TABLE $tableName";
$db->query($queryDelAll);
$queryImport = <<<eof
LOAD DATA LOCAL INFILE '$filePath'
INTO TABLE $tableName
FIELDS TERMINTED BY ','
LINES TERMINATED BY '
'
INGORE 1 LINES
($columnNames)
eof;
$db->query($queryImport);
}
}
and the function that gives the error because of its memory usage.
function toCamelCase($string, $capitalizeFirstCharacter = false) {
$str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
if (!$capitalizeFirstCharacter) {
$str[0] = strtolower($str[0]);
}
return $str;
}
Because the $columnNames
array is only 8 values long I don't know why the memory usage is that high.
Can someone help me out?
Thanks, Per
</div>