开发者

How to convert the date while importing Excel sheet to the database?

I'm having an Excel sheet with the format 01-Mar-10. When I import that csv file into my database it is storing as 0000-00-00. How to convert the dateformat while importing, or is there any other way?

This is the code im using to import to database

        $databasetable = "sample";
        $fieldseparator = ",";
        $lineseparator = "\n";
        $csvfile = "../uploads/" . basename( $_FILES['file']['name']); 
        $addauto = 0;
        $save = 开发者_StackOverflow1;
        $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);


why not use 'LOAD DATA INFILE' with mysql's date formatting?

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

http://dev.mysql.com/doc/refman/5.0/en/load-data.html


$d = "01-Mar-10";
$in_db = date('Y-m-d', strtotime($d));
echo $in_db;

Output:

2010-03-01

Use date() conversion to get valid form of date for storing in database. Use strtotime() to convert excel date format to timestamp.

After exploding data to $linearray use

$linearray[ID]=date('Y-m-d', strtotime($linearray[ID]));

to change it's value to proper format. Replace ID with array index of element with date field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜