upload csv file in php – Read CSV file & Import data into MySQL with PHP

In this “upload csv file in php” tutorial, I will explain to you how to read CSV files with the help of PHP. And how you can import CSV file data into a MySql table with PHP.

So, PHP provides you the method that you can use to read CSV files.

upload csv file in php – Read CSV file & Import data into MySQL with PHP

There are lots of the idea to read CSV files but in this tutorial, i will use two functions to read CSV files fopen() and fgetcsv().

The first method i used to check and read the file with the help of fopen() method with “r” mode. There are many modes of fopen() method you can check all modes at the below link.

fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource

The next method is fgetcsv() this method is specific to read line by line of CSV file and return data into an array. This method is similar to fgets() the only difference is CSV specification.

fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]]] ) : array

upload csv file in php – Import data into MySQL with PHP

So we use these main 2 Methods to extract data from CSV file as well as display into the HTML table and also save into the Database. The below full source code “upload csv file in php” is just an example to show you who CSV data converts into an array with PHP fgetcsv() function.

Read Also:  AngularJS - update bind ng-model input value from Jquery Code

<?php
$data = 1;
if (($handle = fopen("members.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle)) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $data: <br /></p>\n";
        $data++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

And the below source code displays how you read the CSV file as well as display it into the HTML table and save it into the database table.
<table align="center" width="800" border="1" style="border-collapse:collapse; border:1px solid #ddd;" cellpadding="5" cellspacing="0">
    <thead>
        <tr bgcolor="#FFCC00">
            <th>Sr#</th>
            <th>Member Code</th>
            <th>Team Name</th>
            <th>Capital</th>
        </tr>
    </thead>
    <tbody>
    <?php
    if (($handle    =   fopen("member-list.csv", "r")) !== FALSE) {
        $n          =   1;
        while (($data    =   fgetcsv($handle)) !== FALSE){
            if($n>1){
                ?>
                <tr>
                    <td><?php echo $n;?></td>
                    <td><?php echo $data[0];?></td>
                    <td><?php echo $data[1];?></td>
                    <td><?php echo $data[2];?></td>
                </tr>
                <?php
            }
            $n++;
        }
        fclose($handle);
    }
    ?>
    </tbody>
</table>

To save data into the mysql database table first i required to connect with the database so you required to make a connection with the database with PHP consider the below source code.

<?php
$db =   new mysqli('localhost','root','','members');
if ($db->connect_errno) {
  echo "Failed to connect to MySQL: " . $db->connect_error;
  exit();
}
?>

In this best example, i will dump membrs_list’ data into the table to make a database table with the help of the below sql query.

Read Also:  Creating Dynamic Email Template in PHP

--
-- Table structure for table `membrs_list`
--
 
CREATE TABLE `membrs_list` (
  `id` int(5) NOT NULL,
  `memberCode` char(2) NOT NULL DEFAULT '',
  `memberName` varchar(45) NOT NULL DEFAULT '',
  `teamCode` char(3) DEFAULT NULL,
  `employees` varchar(20) DEFAULT NULL,
  `fipsCode` char(2) DEFAULT NULL,
  `isoNumeric` char(4) DEFAULT NULL,
  `pluto` varchar(30) DEFAULT NULL,
  `open` varchar(30) DEFAULT NULL,
  `other` varchar(30) DEFAULT NULL,
  `external` varchar(30) DEFAULT NULL,
  `capital` varchar(30) DEFAULT NULL,
  `serveyName` varchar(15) DEFAULT NULL,
  `servey` char(2) DEFAULT NULL,
  `areaInSqKm` varchar(20) DEFAULT NULL,
  `isoAlpha3` char(3) DEFAULT NULL,
  `geonameId` int(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
 
--
-- Indexes for dumped tables
--
 
--
-- Indexes for table `membrs_list`
--
ALTER TABLE `membrs_list`
  ADD PRIMARY KEY (`id`);
 
--
-- AUTO_INCREMENT for dumped tables
--
 
--
-- AUTO_INCREMENT for table `membrs_list`
--
ALTER TABLE `membrs_list`
  MODIFY `id` int(5) NOT NULL AUTO_INCREMENT;
COMMIT;

To dump some data into the musql database consider the below simple query. You just required to write this easy query into the loop.

<?php
$db->query('INSERT INTO `membrs_list`(`memberCode`, `memberName`, `teamCode`, `employees`, `fipsCode`, `isoNumeric`, `pluto`, `open`, `other`, `external`, `capital`, `serveyName`, `servey`, `areaInSqKm`, `isoAlpha3`, `geonameId`) VALUES ("'.$data[1].'","'.$data[2].'","'.$data[3].'","'.$data[4].'","'.$data[5].'","'.$data[6].'","'.$data[7].'","'.$data[8].'","'.$data[9].'","'.$data[10].'","'.$data[11].'","'.$data[12].'","'.$data[13].'","'.$data[14].'","'.$data[15].'","'.$data[16].'")');
?>

The final complete script.

The complete PHP reads the CSV file and dumps it into the table the is given below.

<?php
$db =   new mysqli('localhost','root','','members');
if ($db->connect_errno) {
  echo "Failed to connect to MySQL: " . $db->connect_error;
  exit();
}
 
if(($handle     =   fopen("membrs_list.csv", "r")) !== FALSE){
    while(($data =   fgetcsv($handle)) !== FALSE){
        $db->query('INSERT INTO `membrs_list`(`memberCode`, `memberName`, `teamCode`, `employees`, `fipsCode`, `isoNumeric`, `pluto`, `open`, `other`, `external`, `capital`, `serveyName`, `servey`, `areaInSqKm`, `isoAlpha3`, `geonameId`) VALUES ("'.$data[1].'","'.$data[2].'","'.$data[3].'","'.$data[4].'","'.$data[5].'","'.$data[6].'","'.$data[7].'","'.$data[8].'","'.$data[9].'","'.$data[10].'","'.$data[11].'","'.$data[12].'","'.$data[13].'","'.$data[14].'","'.$data[15].'","'.$data[16].'")');
    }
    fclose($handle);
}
?>

Don’t Miss : Import CSV File into MySQL using PHP

Read Also:  Codeigniter Paypal Integration Example

How to import csv file in PHP?

The below simple upload csv file in php source code can be used to import CSV file in PHP −

<?php
$data = 1;
if (($handle = fopen("members-list.csv", "r")) !== FALSE) {
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      $num = count($data);
      echo "<p> $num fields in line $data: <br /></p>\n";
      $data++;
      for ($c=0; $c < $num; $c++) {
         echo $data[$c] . "<br />\n";
      }
   }
   fclose($handle);
}
?>


I hope you get an idea about upload csv file in php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.