Tips: export csv files in batches using PHP. 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.
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 is only the main program part for exporting csv files in PHP in batches:
- <? Php
- 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 ";
- ?>
We hope that you can master this technique by using the code example of batch export csv files in PHP.
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. at this time, we can...