Bulk import of data in PHP (CSV file)

Source: Internet
Author: User
Tags define get execution insert query
Data sometimes write a program when the background requirements to import a large number of data into the database, such as computer test results of the query, phone book data are generally stored in Excel, when we can export data into a CSV file, and then through the following program can be in the background batch import data into the database.

The following are just the main program sections:

<?php
/*****************************************
Author: Chong Xing/arcow****************
njj@nuc.edu.cn*******************
PHP import CSV file to database **********
Simultaneous calculation of program execution time ***********
www.knowsky.com***********
****************************************/
Define Get Time function
function Getmicrotime () {
List ($usec, $sec) = Explode ("", Microtime ());
Return ((float) $usec + (float) $sec);
}
?>

<?php
$time _start = Getmicrotime ();
Include ("db.inc.php");//Connect 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 executed successfully! <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 ";
?>



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.