Vonton
Vonton

Reputation: 3344

Insert data from text file (saved in my PC) to tables MySQL

I have one problem, I am totally beginner and I would like Insert or convert data, which I have on my PC like txt file to my tables created by Mysql language. Is it possible? Table has same columns like txt file. Thank you so much

Upvotes: 0

Views: 2836

Answers (2)

chirag dodia
chirag dodia

Reputation: 525

You can write direct sql query Like this

LOAD DATA INFILE 'C://path/to/yourfilename.txt'

INTO TABLE 'database_name'.'table_name'

FIELDS TERMINATED BY ','

LINES TERMINATED BY '\n\r'

(column1,column2)

Here i assumed that your fields are terminated by semi column. for line termination Character and Escape sequence you can take reference from this thread

http://dev.mysql.com/doc/refman/5.1/en/load-data.html

Upvotes: 1

user1709803
user1709803

Reputation:

You can write a simple program that loops through the content of the file and inserts the data into the database. Here is something to get you started.

This simply inserts the data you have put in the PHP code.

What you will want to do is to open a file and insert the data from it

mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
mysql_select_db('db_name') or die(mysql_error());

$lines = file('company.txt');
$company_names = ""; $insert_string = "INSERT INTO company(company_name) VALUES"; $counter = 0; $maxsize = count($lines);

foreach($lines as $line => $company) {

$insert_string .= "('".$company."')"; $counter++; if($counter < $maxsize) { $insert_string .= ","; }//if }//foreach mysql_query($insert_string) or die(mysql_error());

Upvotes: 0

Related Questions