我正在使用格式为01-Mar-10的Excel表格。当我将csv文件导入我的数据库时,它存储为0000-00-00。如何在导入时转换dateformat,还是有其他方法?
这是我用来导入数据库的代码
$databasetable = "sample";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "../uploads/" . basename( $_FILES['file']['name']);
$addauto = 0;
$save = 1;
$outputfile = "../temp/output.sql";
if(!file_exists($csvfile)) {
#echo $csvfile;
echo "File not found. Make sure you specified the correct path.\n";
return 0;
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
#echo "Error opening data file.\n";
return 0;
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
return 0;
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
$line = str_replace("'","\'",$line);
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n";
@mysql_query($query);
答案 0 :(得分:0)
$d = "01-Mar-10";
$in_db = date('Y-m-d', strtotime($d));
echo $in_db;
输出:
2010-03-01
使用date()
转换获取存储在数据库中的有效日期形式。使用strtotime()
将Excel日期格式转换为时间戳。
将数据爆炸到$ linearray后使用
$linearray[ID]=date('Y-m-d', strtotime($linearray[ID]));
将其值更改为正确的格式。用带有日期字段的元素的数组索引替换ID。
答案 1 :(得分:0)
为什么不使用'LOAD DATA INFILE'和mysql的日期格式?
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format