During project development, you often need to import an external CSV file to a database or export the data as a CSV file. How can this problem be solved? This document uses PHP and mysql to import and export CSV data.
During project development, you often need to import an external CSV file to a database or export the data as a CSV file. How can this problem be solved? This document uses PHP and mysql to import and export CSV data.
Prepare the mysql DATA table first. Assume that the project contains a student information table student with the id, name, sex, and age information to record the student name, gender, and age respectively.
The Code is as follows:
Create table 'student '(
'Id' int (11) not null auto_increment,
'Name' varchar (50) not null,
'Sex 'varchar (10) not null,
'Age' smallint (3) not null default '0 ',
Primary key ('id ')
) ENGINE = MyISAM default charset = utf8;
We also need an html interaction page to place the import form and export button.
The Code is as follows:
After selecting the local csv file, click Import and submit it to do. php? Action = import processing, and click Export to request the address do. php? Action = export to export data.
1. Import CSV
Do. php processes the import and export processes based on get parameters. The php structure is as follows:
The Code is as follows:
Include_once ("connect. php"); // connect to the database
$ Action = $ _ GET ['action'];
If ($ action = 'import') // import CSV
{
// Import
} Elseif ($ action = 'Port') // export CSV
{
// Export
}
Process for importing a CSV file: check the validity of the csv file (this document ignores) -> open the fields in the csv file and parse them.-> obtain the values of each field cyclically-> add them to the data table in batches-> complete.
The Code is as follows:
If ($ action = 'import') {// import CSV
$ Filename = $ _ FILES ['file'] ['tmp _ name'];
If (emptyempty ($ filename ))
{
Echo '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 'No data! ';
Exit;
}
For ($ I = 1; $ I <$ len_result; $ I ++) // obtain the Field Values cyclically.
{
$ 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 the pointer
$ Query = mysql_query ("insert into student (name, sex, age) values $ data_values"); // insert data tables in batches
If ($ query)
{
Echo 'import successful! ';
} Else {
Echo 'import failed! ';
}
}
Note that the fgetcsv function provided by php can easily process csv. You can use this function to read a row from the file pointer and parse the CSV field. The following functions parse csv file fields and return them as arrays.
The Code is as follows:
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 we import data to the database, we use batch inserts instead of individual inserts. Therefore, when constructing SQL statements, we need to perform some processing. See the code.
2. Export CSV