PHP text file operation read TXT file save to MySQL database

Source: Internet
Author: User
Tags foreach table name

Instance 1, PHP read TXT file insert database

The code is as follows Copy Code

<?php

$m = mysql_connect (' 127.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 (' &nbsp ', $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 (' 123 ', ' 123 ', 20111014060110765, 1, ' 123 ', ' 123 ', ' 123 ', ' 123 ', ' 123 ', ' 123 ', ' 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 ', ' ba Cktime ', ' Kongju ', ' fengspeed ')
VALUES (' $kanum ', ' $username ', 20111014060110765, $rank, ' $num ', ' $zunum ', ' $sex ', ' $yucolor ', ' $eye ', ' $backtime ', ' $ Kongju ', ' $fengspeed ') or Die ("Invalid query:"). Mysql_error ());
}

?>


PHP read txt file to compose SQL and insert database code

Look at the data structure first

The code is as follows Copy Code
--Data table structure:
--100000_insert,1000000_insert
CREATE TABLE ' 100000_insert ' (
' id ' int (one) not NULL auto_increment,
' ParentID ' int (one) is not NULL,
' Name ' varchar (255) DEFAULT NULL,
PRIMARY KEY (' id ')
) Engine=innodb auto_increment=1 DEFAULT Charset=utf8
100000 (100,000) line insert: Insert 100000_line_data use 2.5534288883209 seconds
1000000 (1 million) line insert: Insert 1000000_line_data use 19.677318811417 seconds


PHP files

The code is as follows Copy Code

<?php
/**
* $splitChar Field Separator
* $file data file filename
* $table database table name
* $conn Database connection
* $fields the corresponding column name of the data
* $insertType insert operation type, including Insert,replace
*/
function Loadtxtdataintodatabase ($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 headers
$end = "')";
$sqldata = Trim (file_get_contents ($file));
if (preg_replace ('/s*/i ', ', ', $splitChar) = = ") {
$splitChar = '/(w+) (s+)/I ';
$replace = "$ ', '";
$specialFunc = ' preg_replace ';
}else {
$splitChar = $splitChar;
$replace = "', '";
$specialFunc = ' str_replace ';
}
Processing the data body, the order of the two is not changed, otherwise the Space or tab separator error
$sqldata = Preg_replace ('/(s*) (n+) (s*)/I ', '), (', $sqldata); Replace line Wrap
$sqldata = $specialFunc ($splitChar, $replace, $sqldata); Replace separator
$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
$file = ' sqldata1.txt ';
$fields = array (' id ', ' parentid ', ' name ');
$table = ' Cengji ';
$result = Loadtxtdataintodatabase ($splitChar, $file, $table, $conn, $fields);
if (Array_shift ($result)) {
Echo ' success!<br/> ';
}else {
Echo ' Failed!--Error: '. Array_shift ($result). ' <br/> ';
}
/*sqlda Ta1.txt
|0| A
|1| B
|1| C
|2| D
--Cengji
CREATE TABLE ' Cengji ' (
' id ' int (one) not NULL auto_increment,
' ParentID ' int (one) is 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 = Loadtxtdataintodatabase ($splitChar, $file, $table, $conn, $fields);
if (Array_shift ($result)) {
Echo ' success!<br/> ';
}else {
Echo ' Failed!--Error: '. Array_shift ($result). ' <br/> ';
}
/* Sqldata2.txt
Aston DB19 2009
Aston DB29 2009
Aston DB39 2009
--Cars
CREATE TABLE ' Cars ' (
' id ' int (one) not NULL auto_increment,
' Make ' varchar is not NULL,
' model ' varchar DEFAULT NULL,
' Year ' varchar 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 = Loadtxtdataintodatabase ($splitChar, $file, $table, $conn, $fields, $insertType);
if (Array_shift ($result)) {
Echo ' success!<br/> ';
}else {
Echo ' Failed!--Error: '. Array_shift ($result). ' <br/> ';
}
/* 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 '; No table exists
$result = Loadtxtdataintodatabase ($splitChar, $file, $table, $conn, $fields);
if (Array_shift ($result)) {
Echo ' success!<br/> ';
}else {
Echo ' Failed!--Error: '. Array_shift ($result). ' <br/> ';
}
Attached: db.php
///Note this line can be completely released
?>
<?php
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 the MySQL server has gone away is due to the import packet is too large, import MySQL hanging machine, our solution is to modify the My.ini/my.cnf max_allowed_packet=20m.

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.