PHP Import and export CSV file to MySQL database method _php Tutorial

Source: Internet
Author: User
Tags bulk insert
Because the job requires that we need to export MySQL data into a CSV file, and then the data provided by the merchant we have to use PHP to import CSV files to the MySQL database, I would like to introduce PHP to import and export CSV files to the MySQL database program code, There is a need to understand the friends can be consulted.


The following is just a simple example

We first prepare the MySQL data table, assuming that the project has a record of student information table student, and there are id,name,sex,age to record the student's name, gender, age and other information.

The code is as follows Copy Code

CREATE TABLE ' Student ' (
' id ' int (one) not NULL auto_increment,
' Name ' varchar (not NULL),
' Sex ' varchar (+) not NULL,
' Age ' smallint (3) is not NULL default ' 0 ',
PRIMARY KEY (' id ')
) Engine=myisam DEFAULT Charset=utf8;

We also need an HTML interactive page to place the import form and export button.

The code is as follows Copy Code

After selecting a good local CSV file, click Import, submit to Do.php?action=import processing, and click the Export button to request the address Do.php?action=export for data export processing.

1. Import CSV

Do.php needs to handle the import and export process separately based on the parameters of Get, PHP structure is as follows:

Include_once ("connect.php"); Connecting to a database

The code is as follows Copy Code
$action = $_get[' action '];
if ($action = = ' Import ') {//import CSV
Import processing
} elseif ($action = = ' export ') {//export CSV
Export Processing
}

Import CSV process: Verify CSV file legitimacy (this article ignores), open read-in and parse fields in CSV file, loop get each field value, and then complete the batch to datasheet.

The code is as follows Copy Code
< P>if ($action = = ' Import ') {//import csv
$filename = $_files[' file ' [' Tmp_name '];
if (empty ($filename)) {
echo ' Please select the CSV file to import! ';
Exit;
}
$handle = fopen ($filename, ' R ');
$result = Input_csv ($handle);//parse csv
$len _result = count ($result);
if ($len _result==0) {
echo ' doesn't have any data! ';
Exit;
}
for ($i = 1; $i < $len _result; $i + +) {//Loop get each field value
$name = Iconv (' gb2312 ', ' utf-8 ', $result [$i][0]);// Chinese transcoding
$sex = iconv (' gb2312 ', ' utf-8 ', $result [$i][1]);
$age = $result [$i][2];
$data _values. = "(' $name ', ' $sex ', ' $age '),";
}
$data _values = substr ($data _values,0,-1);//Remove the last comma
fclose ($handle);//close pointer
$query = mysql_query ("I Nsert into student (name,sex,age) values $data _values ");//Bulk INSERT data Table
if ($query) {
echo ' Import succeeded! ';
}else{
Echo ' Import failed! ';
}
}

Note that PHP's own fgetcsv function makes it easy to work with CSV, which allows you to read a line from the file pointer and parse the CSV field. The following function parses the CSV file field and returns it as an array.

The code is as follows Copy Code

function Input_csv ($handle) {
$out = Array ();
$n = 0;
while ($data = Fgetcsv ($handle, 10000)) {
$num = count ($data);
for ($i = 0; $i < $num; $i + +) {
$out [$n] [$i] = $data [$i];
}
$n + +;
}
return $out;
}

In addition, when importing into a database, we are using bulk inserts instead of inserts, so when you build the SQL statement, you need to handle it a bit, see code.

2. Export CSV

We know that a CSV file is a plain text file made up of comma separators, which you can open with Excel, with the same effect as the XLS table.

Export CSV process: Read the Student information form, looping record building comma-delimited field information, setting header information, export file (download) to local

copy code

...
} elseif ($action = = ' export ') {//export csv
$result = mysql_query ("SELECT * from student ORDER by ID ASC");
$str = "name, gender, age n";
$str = iconv (' utf-8 ', ' gb2312 ', $str);
while ($row =mysql_fetch_array ($result)) {
$name = iconv (' utf-8 ', ' gb2312 ', $row [' name ']);//chinese transcoding
$sex = iconv (' Utf-8 ', ' gb2312 ', $row [' sex ']);
$str. = $name. ",". $sex. ",". $row [' age ']. " n "; Separate
}
with the citation comma $filename = date (' Ymd '). CSV '; Set file name
Export_csv ($filename, $STR);//Export
}

To export the data locally, the header information needs to be modified, with the following code:

The code is as follows Copy Code

function Export_csv ($filename, $data) {
Header ("Content-type:text/csv");
Header ("Content-disposition:attachment;filename=". $filename);
Header (' cache-control:must-revalidate,post-check=0,pre-check=0 ');
Header (' expires:0 ');
Header (' Pragma:public ');
Echo $data;
}

Note the import and export process, because we are using a unified UTF-8 encoding, encountered in Chinese characters must remember transcoding, otherwise there may be garbled in the situation.

PHP Import and export csv file download: Http://file.bKjia.c0m/download/2013/05/15/importCSV.rar

http://www.bkjia.com/PHPjc/630713.html www.bkjia.com true http://www.bkjia.com/PHPjc/630713.html techarticle because the job requires that we need to export MySQL data into a CSV file, and then the data provided by the merchant we have to use PHP to import CSV files to the MySQL database, I would like to introduce to you ...

  • 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.