How to Import CSV file data into MySQL using PHP

This examples shows how to import CSV(Comma Separated Value) file data into MySQL database using PHP. Here we are importing products name and price from CSV file.


First We have to create 'products' table in 'db_sample' database.

CREATE TABLE  `products` (
  `pid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pname` varchar(45) NOT NULL DEFAULT '',
  `price` double(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`pid`)

Sample CSV File Format to Import (fruits.csv)

Import CSV file data into MySQL using PHP


  //MySQL Db Connection
  $con=mysqli_connect($host_name, $user_name, $password, $db_name);


<?php include "config.php"; ?>
    <title>Import CSV file data into mysql using php</title>
    <form method='post' action='importcsv.php' enctype='multipart/form-data'>
        <label>Browse CSV File : </label>
        <input type="file"  name="file" required class="form-control input-sm" accept=".csv">
      <button type="submit" name="submit" class="btn btn-primary btn-sm "><i class="fa fa-save"></i> Submit</button>
        // Allowed types
        $csvTypes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
        $sql="INSERT INTO products(pname,price) VALUES ";
        //Check selected file is csv
        if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvTypes)){
          //file upload
            //Open CSV file with read only mode from tmp
            $file = fopen($_FILES['file']['tmp_name'], 'r');
            // Skip the first line

            //Read CSV data Line by Line
            while(($row = fgetcsv($file)) !== FALSE){
              //Get row data
              //add row values in array
              //add row values in table 
            // Close opened CSV file
            //Display CSV Data In HTML Table
            echo "<table style='border-collapse:collapse;width:250px;' border='1px' cellpadding='5px;'>".$tableRows."</table>";
            //Execute Query
              echo "<h4>Upload Successfully</h4>";
              echo "<h4>Upload Failed</h4>";
            echo "<h4>Upload Failed</h4>";
          echo "<h4>Invalid File</h4>";

Output :

Import CSV file data into MySQL using PHP