aron n
aron n

Reputation: 597

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

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?

Upvotes: 1

Views: 19735

Answers (5)

Tasawer Khan
Tasawer Khan

Reputation: 6148

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

Upvotes: 4

Phill Pafford
Phill Pafford

Reputation: 85298

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
)

Upvotes: 8

Anooj R
Anooj R

Reputation: 19

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.

https://www.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.

Upvotes: 0

Saggio
Saggio

Reputation: 2274

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

Upvotes: 2

mario
mario

Reputation: 145482

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

Upvotes: 0

Related Questions