Sometimes, when writing a program, the background requires that a large amount of data be imported into the database. For example, the computer examination result query and phone book data are generally stored in excel, in this case, we can export the data to a csv file, and then use the following program to import data to the database in batches in the background.
The following are the main program parts:
<? Php
/*************************************** **
* ******** Author: Chong Xing/arcow ****************
*******************
* ********* Import a csv file to the database in php **********
***********
* ********* Www.knowsky.com ***********
****************************************/
// Define a time function
Function getmicrotime (){
List ($ usec, $ sec) = explode ("", microtime ());
Return (float) $ usec + (float) $ sec );
}
?>
<? Php
$ Time_start = getmicrotime ();
Include ("db. inc. php"); // connect to the database
$ 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 statement execution successful! <Br> ";
$ SQL = "insert into scores (idcard, names, num, sex, nation, score) values ('";
}
Fclose ($ handle );
$ Time_end = getmicrotime ();
$ Time = $ time_end-$ time_start;
Echo "program execution time:". $ time. "seconds ";
?>