php中數(shù)據(jù)的批量導(dǎo)入(csv文件)
有時寫程序時后臺要求把大量數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫中,比如計算機(jī)考試成績的查詢、電話簿的數(shù)據(jù)等一般都是存放在excel中的,這時我們可把數(shù)據(jù)導(dǎo)出成csv文件,然后通過以下程序即可在后臺批量導(dǎo)入數(shù)據(jù)到數(shù)據(jù)庫中。
下面只是主要程序部分:
<?php /***************************************************作者:沖星/arcow**************************[email protected]*****************************php導(dǎo)入csv文件到數(shù)據(jù)庫********************同時計算程序執(zhí)行時間*********************www.mypchelp.cn***************************************************///定義獲取時間函數(shù) function getmicrotime(){ list($usec, $sec) = explode(' ',microtime()); return ((float)$usec + (float)$sec); }?>
<?php$time_start = getmicrotime();include('db.inc.php');//連接數(shù)據(jù)庫$db=new testcsv;?><?php$handle = fopen ('test.csv','r');$sql='insert into scores(idcard,names,num,sex,nation,score) values('';while ($data = fgetcsv ($handle, 1000, ',')) { $num = count ($data); for ($c=0; $c < $num; $c++) { if($c==$num-1){$sql=$sql.$data[$c].'')';break;} $sql=$sql.$data[$c].'',''; }print '<br>';echo $sql.'<br>';$db->query($sql);echo 'SQL語句執(zhí)行成功!<br>';$sql='insert into scores(idcard,names,num,sex,nation,score) values('';}fclose ($handle);$time_end = getmicrotime();$time = $time_end - $time_start;echo '程序執(zhí)行時間:'.$time.'秒';?>
