Assuming the first (non-empty) line of the CSV file has the column names, I might do something like this (too much time on my hands today):
<?php
$allowedColumns = array(
'Firstname',
'Lastname',
'Dob',
'Col'
);
mysql_connect('localhost', '#####', '#####') or die(mysql_error());
mysql_select_db('the_db') or die(mysql_error());
$file = 'documents/csvs/' . $file_name;
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($lines as $key => $line) {
$lines[$key] = explode("\t", $line);
}
$columns = array_shift($lines);
$intersect = array_intersect($columns, $allowedColumns);
if(count($intersect) != count($allowedColumns)) {
die("Wrong columns");
}
array_walk(
$columns,
create_function(
'&$value,$key',
'$value = "`" . mysql_real_escape_string($value) . "`";'
)
);
$sql = "INSERT INTO `mytable` (" . implode(', ', $columns) . ") VALUES\n";
foreach($lines as &$line) {
array_walk(
$line,
create_function(
'&$value,$key',
'$value = (is_numeric($value)) ? $value : "\'".mysql_real_escape_string($value)."\'";'
)
);
$line = "(".implode(', ', $line).")";
}
$chunks = array_chunk($lines, 10); // process 10 at a time
foreach($chunks as $chunk) {
$thisSql = $sql . implode(",\n", $chunk);
mysql_query($thisSql) or die(mysql_error());
}