Transfer data from CSV file to MySql Database


Programmer often need to insert data from CSV file to Mysql Database. This can be simply done using the below sample code. To import CSV File to MYSQL Database, first we will connect to database, open up a csv file, get data from each row and insert them to mysql database.

In first stage, we will only connect to the database. In second stage we will insert the Excel data to database. Let look at my database connection file named as dbconnection.php

Database Connection

The above code is just a connection to database. The actual insertion code lies in below code. For simplicity, I have commented main lines of codes. Here is my index.php file for inserting data from CSV file to Mysl Database.


Lines number 4, 5 and 6 is for enabling the error message if any. Line 9 calls the dbconnection.php file for database connection. Line 12 with fopen(countries.csv) opens a csv file with read access only. You can find more about the fopen at

$flag is used to escape the first row of CSV file because it contains title but not the data. fgetcsv is used to fetch the data from csv file. It will return an array. So, we are accessing each column data with array as $data[0] and $data[1]. Line 29 and 33 makes query to insert to database and execute simultaneously. IGNORE in sql statement is for preventing duplicate entry of data. During the insertion process, we are echoing messages. You can download the CSV file by clicking here

Strong Recomendation: Please use either PDO or MYSQLI. You can find resources at

Read More Articles


  1. Hi there! I just wanted to ask if you ever have any issues
    with hackers? My last blog (wordpress) was hacked and
    I ended up losing many months of hard work due to no data backup.
    Do you have any methods to protect against hackers?

  2. It is appropriate time to make a few plans for the longer term
    and it’s time to be happy. I have read this publish and if
    I could I desire to recommend you some fascinating issues or suggestions.
    Perhaps you could write next articles regarding this article.

    I desire to read more things about it!

  3. Good post. I learn something new and challenging on sites
    I stumbleupon on a daily basis. It’s always exciting to read through
    articles from other authors and practice a little something
    from other sites.


Please enter your comment!
Please enter your name here