How do I read this text file and Insert into MySQL

2019-01-27 06:52发布

问题:

sample

user id  User Name
   U456      Mathew 
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane

and so on up to 500k.

I need to read this text file and insert to MySQL in two columns say User ID and User Name. How do I do this in PHP?

回答1:

LOAD DATA INFILE

Example:

NOTE: if you run this from Windows you need to escape the forward slashes in the file path.

EXAMPLE:

C:\\path\to\file.txt

Looks like:

C:\\\\path\\to\\file.txt

Here is the query:

LOAD DATA INFILE '/path/to/sample.txt' 
INTO TABLE `database_name`.`table_name` 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(
user_id, user_name
)


回答2:

Using PHP, Possibly Something similar to this:

$file = "/path/to/text/file.txt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);

The above reads the text file into a variable

$output = explode("\n", $output);
foreach($output as $var) {
$tmp = explode("|", $var);
$userId = $tmp[0];
$userName = $tmp[1];

Tell it to explode at each Endline and then store the data in temp variables

$sql = "INSERT INTO table SET userId='$userId', userName='$userName'";
mysql_query($sql);

Execute the query for each line



回答3:

Delete the first line and use this command

LOAD DATA INFILE 'C:\\sample.txt' 
INTO TABLE Users 
FIELDS TERMINATED BY ' '  
LINES TERMINATED BY '\r\n';

For more information visit http://tech-gupshup.blogspot.com/2010/04/loading-data-in-mysql-table-from-text.html



回答4:

Depends. If the two fields are separated using a TAB character, then fgetcsv($f,1000,"\t") would work to read in each line. Otherwise use substr() if it's a fixed width column text file to split up the fields (apply trim() eventually).

Loop over the rows and fields, and use your database interface of choice:

db("INSERT INTO tbl (user_id, user_name) VALUES (?,?)", $row);


回答5:

Use the fopen function of PHP to access and read the file.. From there on the rest is pretty much simple. Read the file line by line and insert the values into the database.

http://us3.php.net/manual/en/function.fopen.php

The above link gives a very good description of how the fopen function works.. Using a loop will be easy in this task.