Php Text File Operation Read txt file save to mysql database-PHP source code

Source: Internet
Author: User
This article adds two related implementations to your favorites. You can use php fopen to open a text file and save it to the database. The method is simple. Let's take a look. This article adds two related implementations to your favorites. You can use php fopen to open a text file and save it to the database. The method is simple. Let's take a look.

Script ec (2); script

Instance 1. php reads txt files and inserts them into the database

The Code is as follows:

$ M = mysql_connect ('1970. 0.0.1 ', 'root', '') or die (" Invalid query: ". mysql_error ());

Mysql_select_db ('discuz', $ m) or die ("Invalid query:". mysql_error ());


$ Handle = fopen ("aa.txt", "r ");
While (! Feof ($ handle )){
$ Buffer = ($ handle );
$ Ss [] = explode ('', $ buffer );

}
// Var_dump ($ ss );

Mysql_query ("set names 'utf8'", $ m );
Foreach ($ ss as $ k => $ v ){
// Addslashes ($ v );
// Foreach ($ v as $ k = $ value ){
// $ Vv = addslashes ($ value );
// Mysql_query ("insert into match_view_test_2 ('kanum', 'username', 'mid ', 'rank', 'num', 'zunum', 'sex ', 'yucolor', 'eye ', 'backtime', 'kongju', 'fengspeed ')
// Values ('20170301', '20170301', 123, 1, '20160301', '20160301', '20160301', '20160301 ', '123', '123') ") or die (" Invalid query :". mysql_error ());
//}
$ Kanum = $ v [1];
$ Username = $ v [2];

$ Rank = (int) $ v [0];

$ Num = $ v [3];
$ Zunum = $ v [4];
$ Sex = $ v [5];
// Echo $ sex;
$ Yucolor = $ v [6];
// $ Eye = $ v [7];
$ Backtime = $ v [8]. ''. $ v [9];
$ Kongju = $ v [10];
$ Fengspeed = $ v [11];
Mysql_query ("insert into match_view_test ('kanum', 'username', 'mid ', 'rank', 'num', 'zunum', 'sex', 'yucolor ', 'eye ', 'backtime', 'kongju', 'fengspeed ')
VALUES ('$ kanum',' $ username', 20111014060110765, $ rank, '$ num',' $ zunum', '$ sex', '$ yucolor ', '$ eye', '$ backtime',' $ kongju ',' $ fengspeed ') ") or die (" Invalid query :". mysql_error ());
}

?>


Php reads the txt file to form an SQL statement and inserts the database code

First look at the data structure

The Code is as follows:
-- Data table structure:
-- 100000_insert, 1_00_insert
Create table '2017 _ insert '(
'Id' int (11) not null AUTO_INCREMENT,
'Parentid' int (11) not null,
'Name' varchar (255) default null,
Primary key ('id ')
) ENGINE = InnoDB AUTO_INCREMENT = 1 default charset = utf8
Insert 100000 (0.1 million) rows: Insert 100000_line_data use 2.5534288883209 seconds
Insert 1000000 (1 million) rows: Insert into 00_line_data use 19.677318811417 seconds


PHP File

The Code is as follows:

/**
* $ SplitChar field delimiter
* $ File data file name
* $ Table database table name
* $ Conn database connection
* $ Name of the column corresponding to fields data
* $ InsertType INSERT operation type, including INSERT and REPLACE
*/
Function loadtxtdata1_database ($ splitChar, $ file, $ table, $ conn, $ fields = array (), $ insertType = 'insert '){
If (empty ($ fields) $ head = "{$ insertType} INTO '{$ table} 'values ('";
Else $ head = "{$ insertType} INTO '{$ table }'("'. implode ('','', $ fields ). "') VALUES ('"; // data Header
$ End = "')";
$ Sqldata = trim (file_get_contents ($ file ));
If (preg_replace ('/s */I', '', $ splitChar) = ''){
$ SplitChar = '/(w +) (s +)/I ';
$ Replace = "$1 ','";
$ SpecialFunc = 'preg _ replace ';
} Else {
$ SplitChar = $ splitChar;
$ Replace = "','";
$ SpecialFunc = 'str _ replace ';
}
// Process the data body. The order of the two parts cannot be changed. Otherwise, an error occurs when the space or Tab separator is used.
$ Sqldata = preg_replace ('/(s *) (n +) (s *)/I', ''), ('', $ sqldata); // replace line feed
$ Sqldata = $ specialFunc ($ splitChar, $ replace, $ sqldata); // replace the delimiter
$ Query = $ head. $ sqldata. $ end; // data stitching
If (mysql_query ($ query, $ conn) return array (true );
Else {
Return array (false, mysql_error ($ conn), mysql_errno ($ conn ));
}
}
// Call Example 1
Require 'db. php ';
$ SplitChar = '|'; // vertical bar
$ File = 'sqldata1.txt ';
$ Fields = array ('id', 'parentid', 'name ');
$ Table = 'cengji ';
$ Result = loadtxtdata1_database ($ splitChar, $ file, $ table, $ conn, $ fields );
If (array_shift ($ result )){
Echo 'success!
';
} Else {
Echo 'failed! -- Error: '. array_shift ($ result ).'
';
}
/* Sqlda ta1.txt
| 0 |
| 1 | B
| 1 | C
| 2 | D
-- Cengji
Create table 'cengji '(
'Id' int (11) not null AUTO_INCREMENT,
'Parentid' int (11) not null,
'Name' varchar (255) default null,
Primary key ('id '),
Unique key 'parentid _ name_unique '('parentid', 'name') USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1602 default charset = utf8
*/


// Call Example 2
Require 'db. php ';
$ SplitChar = ''; // Space
$ File = 'sqldata2.txt ';
$ Fields = array ('id', 'make', 'model', 'Year ');
$ Table = 'cars ';
$ Result = loadtxtdata1_database ($ splitChar, $ file, $ table, $ conn, $ fields );
If (array_shift ($ result )){
Echo 'success!
';
} Else {
Echo 'failed! -- Error: '. array_shift ($ result ).'
';
}
/* Sqldata2.txt
Aston DB19 2009
Aston DB29 2009
Aston DB39 2009
-- Cars
Create table 'cars '(
'Id' int (11) not null AUTO_INCREMENT,
'Make' varchar (16) not null,
'Model' varchar (16) default null,
'Year' varchar (16) default null,
Primary key ('id ')
) ENGINE = InnoDB AUTO_INCREMENT = 14 default charset = utf8
*/
// Call Example 3
Require 'db. php ';
$ SplitChar = ''; // Tab
$ File = 'sqldata3.txt ';
$ Fields = array ('id', 'make', 'model', 'Year ');
$ Table = 'cars ';
$ InsertType = 'replace ';
$ Result = loadtxtdata1_database ($ splitChar, $ file, $ table, $ conn, $ fields, $ insertType );
If (array_shift ($ result )){
Echo 'success!
';
} Else {
Echo 'failed! -- Error: '. array_shift ($ result ).'
';
}
/* Sqldata3.txt
Aston DB19 2009
Aston DB29 2009
Aston DB39 2009
*/
// Call Example 3
Require 'db. php ';
$ SplitChar = ''; // Tab
$ File = 'sqldata3.txt ';
$ Fields = array ('id', 'value ');
$ Table = 'notexist'; // The table does not exist.
$ Result = loadtxtdata1_database ($ splitChar, $ file, $ table, $ conn, $ fields );
If (array_shift ($ result )){
Echo 'success!
';
} Else {
Echo 'failed! -- Error: '. array_shift ($ result ).'
';
}
// Appendix: db. php
/* // Note that all rows can be released.
?>
Static $ connect = null;
Static $ table = 'jilian ';
If (! Isset ($ connect )){
$ Connect = mysql_connect ("localhost", "root ","");
If (! $ Connect ){
$ Connect = mysql_connect ("localhost", "Zjmainstay ","");
}
If (! $ Connect ){
Die ('can not connect to database. Fatal error handle by/test/db. php ');
}
Mysql_select_db ("test", $ connect );
Mysql_query ("set names utf8", $ connect );
$ Conn = & $ connect;
$ Db = & $ connect;
}
?>

If MySQL server has gone away is generated because the imported data packet is too large and the mysql instance is being imported, We can modify my. ini/my. cnf max_allowed_packet = 20 M.

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.