How to Upload CSV and Save in Mysql database using PHP

New to php and don’t know how to upload and save CSV file in mysql database? Don’t worry in this post I am going to discuss with you how to do that.

Before I jump into the code let’s see what we are going to do.

Steps: How to upload CSV and save in Mysql database using PHP

  • Create a html form with input file field.
  • Add some CSS Style
  • Create connection to database.
  • Create table in which we will save CSV data.


When we want to add file field in the form then we must add enctype=”multipart/form-data”. Enctype attribute identifies how the form data should be encoded when data is going to server and it can be used only if the form method is POST. $_GET[‘file’] will use to print success message and $errorMsg will print error message if file will not a CSV.


Mysql Table Structure

I am using some php built-in function to accomplish CSV Upload task here they are:

  • Pathinfo (path,options): returns path information in array form. It takes 2 parameters. First is file path which is required and second is options parameter which is optional.
  • move_uploaded_file(file,newloc): moves uploaded file into new location. It also takes 2 required parameters. First parameter specifies the file to be moved and second specifies the new location of the current uploaded file.
  • fopen(filename,mode,include_path,context): opens a file or URL. If file or URL not exist it returns FALSE. Fopen() function takes 4 parameter filename and mode are required parameter, include_path and context are optional parameter. If you want to discover more about fopen then visit fopen().
  • fgetcsv(file,length,separator,enclosure): parses a line from an open file and returns array of each row in CSV file. fgetcsv() takes 4 paramter. First parameter is required and rests of three are optional.

PHP Code


Posted in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *