See what you think of this:
<?php
/**
* Read some number of records from CSV file and convert to array
* of SQL value expressions, e.g.: "('val1', 'val2', 'val3')"
* @param resource $fileHandle fopen() file handle
* @param integer $numFields number of fields for each record
* @param integer $numRows number of rows to read
* @param boolean $eof true if end-of-file reached, else false
* @param string $delimiter CSV file field delimiter
* @return array
*/
function getValuesFromCsv(
$fileHandle,
$numFields,
$numRows=50,
&$eof,
$delimiter=','
) {
$eof = false;
$numFields = (int)$numFields;
$numRows = max(1, (int)$numRows);
$values = array();
$row = 1;
for($row = 1; $row <= $numRows; $row++)
{
$line = fgetcsv($fileHandle, 40000, $delimiter);
if($line === false)
{
$eof = true;
break; // end of csv file
}
if(count($line) < $numFields)
{
$row--;
continue; // skip, not enough fields (maybe add error_log()?)
}
$fields = array();
for($ix = 0; $ix < $numFields; $ix++)
{
$fields[] = (is_numeric($line[$ix])) ? $line[$ix] :
"'".mysql_escape_string($line[$ix])."'";
}
$values[] = "(".implode(', ', $fields).')';
}
return $values;
}
// connect to DB
require_once('DatabaseConnection.php');
mysql_select_db($database_DatabaseData, $DatabaseData);
//open file read only
$file=fopen("../DelimitedData.txt","r");
$eof = false; // init. end-of-file flag
do {
// get array of insert value expressions:
$values = getValuesFromCsv($file, 5, 50, $eof, '|');
if(count($values))
{
// implode values into comma-separated sequence:
$insertSQL = "INSERT INTO table (Col1, Col2, Col3, Col4, Col5) VALUES " .
implode(",\n", $values);
$Result1 = mysql_query($insertSQL, $DatabaseData) or die(mysql_error());
}
}while(!$eof);
?>