Importing CSV (spreadsheet) data into a MySQL Database using PHP

Working with CSV files is very common practice, as such you’ll want to add data from spreadsheets into a database, this tutorial will show you how to do just that.

For this tutorial where going to work with a sample CSV file, which has the following fields: First Name, Last Name, Email

You can download the sample CSV file. Before we start writing the script we first need a database table to store the data,

Create the following table you can do this via phpmyadmin or run the following code in a php page (remember to connect to the database beforehand)

now we have a CSV file to work with and a database table to save the data to it’s time to write the script that will do all the heavy lifting for us.

The first thing to do is connect to your database, supply the host, database username, password and the database name your going to use.

Next we create a function to detect the file extension as we only want to allow uploads of .CSV files, This function returns the file extension for us to work with later in the script.

The next function fetching any errors that have been created that are stored in an array called $error, the function loops through all errors in the array, add them to a variable called $showError and then returns the errors to be used when the function is called.

Next we detect if the upload form has been submitted by checking the name of the submit field in a $_POST next a check is down to determine the file extension and if the extension is not csv an error is created, which will stop the upload and show the error to the user.

If the file is a csv file the script carries on.

Next a variable called $tot is created with a value of 0 this will increment on each loop to give us the total number of rows inserted into the database.

The next step is to open the uploaded file using fopen() passing it the uploaded file and set the mode, in this case ‘r’ for read. Then loop through all the data.

The easiest way of doing this is by making use of php’s fgetcsv function. Pass the function the handle (references fopen) how many bites to read and the separated for csv’s this will be a comma.

Next we perform a for loop then you can determine what data you have by using pre tags and print_r($data) which will print out the array indexes, this is commented out as we’re not using it, to see the array’s index uncomment the 2 lines.

Next insert the data into a databsase, select the table to use then the fields to insert into along with their value, I’ve escaped the data using a function called mysql_real_escape_string() to prevent any security concerns, for each piece of data you need to specify the index in the array $data[0], $date[1]..ect

To have the query only run for the csv data and not the headers an if statemebt can help by only allowing thw query to run where the $data[0] is not equal to the contents of the header such as firstname

At the end of the loop the $tot increments

Next close the while loop and close the handle for fopen, then create a success message including the total number of rows added.

close the if no errors if statement and if the if statement for if the form has been submitted.

Next call the errors function passing it the error array add this to variable then start forming the display area of the form, make sure the form is using enctype=”multipart/form-data” and it’s method is set to post, then create the upload field in the form and a submit button.

Then finally output the contents of the variable $content.

Here’s the full script:

 

  • http://www.facebook.com/profile.php?id=1766666589 Mike Grunow

    Is it possible to loop through each row and say for example enter the first two values get the mysqli_insert_id and add that and the next few values to a different table?

    • http://www.daveismyname.com David Carr

      yes it is, all you would need to do is perform the insert for the first 2 fields then after that query do another insert using the id from the first query, each loop of $data is the row records being imported.

  • Pewe

    I have a program which creates a csv from an .sdf file.

    In doing so the first line of the csv is the table field headers.

    Would it be possible to modify this script to ignore the first line when adding to the mySql database – if so – how?

    • http://www.daveismyname.com David Carr

      yes pick a column to use say you have the first colum called Title for example you use an if statement to only run the query the the data index 0 is not equal to Title like:

      if($data[0] !=’Title’){
      //sql here
      }

      • Pewe

        David,
        Your speedy response is much appreciated – that did the trick.

        Just as a thought – as your sample CSV has headers in the first line – adding this mod for the script to your article may help others who read it.

        • http://www.daveismyname.com David Carr

          Good call I will update it.

          • Pewe

            David,

            Sorry to be a pain if I am wrong, but should the line

            - if($data[0] !=’firstname’){

            read

            if($data[0] !=’First Name’){

            To reflect the info in the csv file???

            Also, could you explain the ‘values’ in a bit more detail for me (I have practically no experience of coding, let alone mysql stuff.

            I want to add more columns to the table and am not sure about the ‘numbering’ – ie ($data[3]) etc.

    • ramkrishna

      hello…are u still struggling with removing the first header from csv file ( not to read ) …here is what i have tried and it works great….
      $count = 0;
      while($line = fgetcsv(…..)) {
      $count++;
      if( $count == 1) { continue; }

      }