Import CSV data file into MySQL using PHP

Home » Computer » Import CSV data file into MySQL using PHP

Import CSV data file into MySQL using PHP

CSV files are known as comma separated values. It is one of the most preferred data storage methods. PHP supports various data formats like csv, json etc. and provides functions to handle such data formats. We can parse and store csv records in database using core PHP.

Steps to import data from CSV data file to MySQL.

Step 1: Create MySQL Database
Login to phpmyadmin
Create a new database ‘classes’ in MySQL. Next create a table ‘students’ to store the details of the students in the classes database.
Run the below command to create table students inside classes database.


Step 2: CSV file
Check the students csv file and structure. This data is going to get imported to MySQL.


Step 3: Add database details
Add proper database details into the connection file.


Step 4: Putting it all together
Create a folder ‘phpimporter’ and place it inside the www folder. Add students.csv, db_config.php and index.php file to phpimporter project and paste the below code in index.php file.

Here $data[0], $data[1] are the columns in the csv. The mapping should be proper into to insert the data properly.
If you don’t want to hardcode the data as $data[0], $data[1]. check the alternate solution below


Step 5:Output
Run the project as http://localhost/phpimporter on the browser.
Check the database it should show the data present in csv is imported properly in MySQL students table.