How do I read this text file and Insert into MySQL?

懵懂的女人 提交于 2019-11-29 08:49:41

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
)

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

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

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!