Batch import of data in php (csv file) _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Batch import of data in php (csv file ). 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 import a large amount of data into the database when writing a program. for example, the query of computer examination scores and the data in the phone book 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:

/*************************************** **
* ******** 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 );
}
?>

$ Time_start = getmicrotime ();
Include ("db. inc. php"); // connect to the database
$ Db = new testcsv;
?>
$ 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"
";
Echo $ SQL ."
";
$ Db-> query ($ SQL );
Echo "SQL statement execution successful!
";
$ 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 ";
?>

...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.