insert in mysql table from .txt file

mysql, php

Solution

You certainly can do it via a PHP script, but the best way is to use the Mysql `load data infile` syntax like this:

LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test
  FIELDS TERMINATED BY ','  LINES TERMINATED BY '\n';

In you case, it looks like the fields are terminated by `:` so you can change it easily enough like this:

LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test
  FIELDS TERMINATED BY ' : '  LINES TERMINATED BY '\n';

You can run this command from any mysql query function by inserting it as the query. This will be much faster than anything you can do in PHP manually (as in reading the text into PHP, then inserting it into the database).

Edit: Be aware that if you use this in a string, you will need to escape the `\` in the newline character with another `\` like this: `LINES TERMINATED BY '\\n';`

Problem

i have a situation where i have to insert in mysql table from a .txt file. and data is in format of below. both the data from left and right show seperatly insert into 2 columns. and the 3rd colum show be id ``` koijjh12 : 12 lkoiujjf : 12 uoytresf : 15 kjhgfd56 : 50 ``` can we use php script to import that .txt file to the mysql database.

Original source