PHP read text file and insert into MySQL database

Today I was working on an in house project and suddenly one of my colleagues came to me with a text file and said please import this file into database. I did that for him.

At a same time I got an idea why not this small task should share with my PHP beginners. So in this tutorial I am going to show how to read text file and insert into mysql database.

Read text file and insert into MySQL database

First let me show you some of the built-in php functions which I am going to use in this process.

  • fopen() : Open a file or url. fopen() takes2 arguments. First argument is a file name or url and second argument is mode. Mode parameter specifies the type of access you require to the file.
  • feof() : Checks the end of file is reached or not.
  • fgets() : Returns a line from an open file.
  • explode() : Breaks string into an array. It takes 2 arguments. First argument is a separator and second is string.
  • list() : Assign variables as if they were an array.
  • fclose() : Close the open file.

Create Database:

Create Database Table:

Text file content:

Database Connection:

Read text file and insert data:

In the above code first I open a employee-data.txt using reading (r) mode. Then I used while loop using feof() function and make sure loop must be iterated till the end of file. Then I stored file line in the $getTexLine variable and then convert that line into an array by using comma. I already knew that we have 4 type of data on each line so I used list() function and create 4 variables which are $name, $city, $postcode, $job_title. After that I create a mysql insert statement and add data into table. This process will continue until employee-data.txt content ends.

Also read:

 

Posted in PHP

Author: Ahsan Zameer

I am a web developer and love to search new stuff on web. Trying different approaches and ideas to make web developing more interesting and enjoyable.