I have the function listed below from the File Importer class by Md. Kausar Alam on PHPClasses.orgfor importing CSV or tab delimited files directly into my database table. The problem I have is that some people do not have the columns in the same order as they are in the table.
I have built a configuration utility for them to "tell" us how their file is configured (formatted). The default format of the configuration is 1|2|3|4|5|6|7 where the numbers represent the position of our database columns in reference to the columns in their file. For instance, this is our default column layout:
PartNo, AltPartNo, CondCode, Qty, Descr
If a customer has a file formatted like this: PartNo, Descr, Qty, Other,
CondCode, AltPartNo, Other2
Their numbering would be 1|5|4|6|3|2|7
I am allowing them to have at least 2 columns extra in their format.
How would I modify the function below to use the customer's layout for the importing of their data, basically changing the ordering of the $fieldsValues so they will be imported correctly? Is this something where I can use usort to reorder the array elements?
In the function call, the $fields array is the array of columns from the database obtained from INFORMATION_SCHEMA.COLUMNS. The $fieldsValues is the line from the CSV/TabDelimited file being imported.
public function insertDataIntoTable( $fields, $fieldsValues )
{
if (!strpos(strtolower($fieldsValues[0]), 'number')) {
if(strlen(trim($fieldsValues[0])) > 0) {
$sql = 'INSERT INTO ' .$this->tableName;
$values = " VALUES (null, ".$this->userid.", ";
$u = 1;
foreach($fieldsValues as $key => $value) {
if($u <=5){
if ($this->separator ==',') {
$values .= "'" .str_replace('"', '', trim($value)) ."', ";
} else {
$values .= "'" .trim($value) ."', ";
}
}
$u++;
}
$query = $sql;
$values = substr( trim($values), 0, -1);
$query = $query .' '. $values .", NOW(), '', '');";
mysql_query( $query ) or die("<br>".$query."<br>".mysql_error());
}
}
}