Import Data from CSV File to MySQL Using PHP

How to Import Data from CSV File to MySQL Using PHP
Written by Yogesh Koli

Import CSV data to MySQL


Do you want to import data from CSV file to MySql Database using PHP?

Probably every PHP developer needs to deal with CSV file import (we also called it as a comma separated data). So basically developer needs get the data from the CSV file and insert into the MySQL database.

In this tutorial I am going to help to import data easily from CSV file using a very basic PHP script

Let’s start with the basic example:

Sample CSV File to Import:

Here we are importing users from users.csv file, take a look at below file, which is having basic details of users like Name, Mobile Number and Email address.

Records from users.csv file


of course this is just a demo, you can use your own file to import with any format or number of columns just make sure to focus on each column accordingly

let go to the next step:

Create MySQL Sample Database and required Table for this example:

We have our CSV file ready with record set, now we need to create MySQL database table to store the records, go ahead and create table using following SQL query:

Users Table Structure

Users Table Structure

Create PHP MySQL Database connection File:

Create database connection file called db_connection.php to connect MySQL.

Use following code to and make sure to update connection variables with your server configuration

PHP Script to Import CSV File Data:

Create import.php file: this is the user interface where we are going to have feature to select and submit file to the server.


Import Data from CSV UI

We are done, try to run your code or you can easily download tutorial code from following links. let me know if you find any difficulty running the code or getting any issues.

If you want to export data from MySQL to CSV file you learn from here – Export Data from MySQL to CSV using PHP

About the author

Yogesh Koli

Yogesh Koli is a software engineer & a Blogger lives in India. He's driven by an addiction to learning and a love for adventure. he has 5+ years of experience working with the front-end, back-end, web application development, and system design.

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Vijay Pavan Kumar Kudupudi Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

newest oldest most voted
Notify of
Vijay Pavan Kumar Kudupudi
Vijay Pavan Kumar Kudupudi

is there any script to Upload csv file to DB and it has to check duplicate fields