Import and export csv file in database using php tutorial

Hi, There! We have an another concept of comma separated values file’s data insertion. Many times, we have to store a large amount of data in database,but it becomes a very infeasible task as it consumes a large amount of time. So, to automate this task, many website provides a facility to store a bulk data by simply uploading a csv file and the data is then stored efficiently. We’ll here see how the data can be import from the files to database and export from database to files.

What is csv file?

It stands for “Comma Separated Values”. It is nothing but an excel sheet in which the data is stored in rows and columns.
This tutorial will show both importing data from csv to database and exporting the data from database to csv. So lets start by creating the database named csv_import_export and run query as follows.

Create connection using config.php as follows. We are using a PDO connection method in php here. Because it is a secure and prevents sql injections.

The values are assigned to the variables and they are used in the PDO function. Make sure you have replaced the values of hostname, username, database name and passwords with your ones.

Now create main file as index.php and add the following code in it.

This file contains the front end view and a form is inserted. The dialog box opens to upload and download files by clicking on the respective links.

You’ll see the following view of index.php.

 

csv import export using php mysql

However, the views will not work for now. We’ll make it work by coding further. So, continue…

Import comma separated values file

Now create file import.php and paste following code in it. This is the main configuration code used for importing the data into the database.

Export csv file

Lets code export.php as follows. The below code snippet will be used for exporting the data form the database and put into rows and columns.

You’ve seen a styling in the above screenshots. Here’s how it is done using style.css as follows.

That’s it! We’ve finished our coding part. You can see the dialog box for choosing files as follows. Give it a try and feel free to use the code in your projects.

csv import export using php mysql

 

Now your code should be working fine. Thanks for reading this tutorial.
For additional JavaScript files and source files, you can download the source code from the below link.

You can directly download the full working source code from the below link.

Download Source code

Please provide your feedback in the comments section below.

Leave a Reply

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