Ok, so the other day I did a php script to export any table to csv,. well I was thinking it sure would be sweet to also be able to import from csv to any table.
function csv2talbe($sourceFile,$tableName,$maxLine=1000){
global $errors;
$fileHeadings = array();
$tableHeadings = array("fields","from","import","table");
if( ($handle = fopen("$sourceFile","r") ) !== false ){
$columns = fgetcsv($handle, $maxLine, ",");
foreach( $columns as $col ){
$fileHeadings[] .= $col;
}
$qPrefix = "insert into $targetTable (" .join(",",$tableHeadings).")\n VALUES";
while(( $data = fgetcsv($handle, $maxLine, ",")) !== false ){
while( count($data) < count($columns) )
array_push($data, NULL);
$query = "$qPrefix (".join(",",quote_all_array($data)).");";
mysql_query($query);
if( mysql_error() != '' ){
$errors = true;
$error_txt .= "<p>" . mysql_error() . "</p>";
}
}
fclose($handle);
}
if( $errors === false ){
$q = mysql_query("truncate {table to be updated}");
$q = mysql_query("insert into {table to be inserted} (dateUpdated,success,failure) values(curdate(),'Success','');
if( mysql_error() != '' ){
$errors = true;
$error_txt .= "<p>" . mysql_error() . "</p>";
} else {
$q = mysql_query("insert into {updatetable} (dateUpdated,success,failure) values(curdate(),'success','');
if( mysql_error() != '' ){
$errors = true;
$error_txt .= "<p>" . mysql_error() . "</p>";
}
}
}
if( $errors === true ){
mail("youremail@yourdomain.com","your name","subject","message . $error_txt");
} else {
mail("youremail@yourdomain.com","your name","subject","message success");
}
function quote_all_array($values){
foreach($values as $key=>$value)
if( is_array($value) )
$values[$key] = quote_all_array($value);
else
$values[$key] = quote_all($value);
return $values;
}
function quote_all($value){
if( is_null($value))
return "NULL";
$value = "'" . mysql_real_escape_string($value) . "'";
return $value;
}
// and that pretty much does it...