Import excel data into database using PHP

Kailash Singh

Import excel data into database using PHP

Published Oct 25,2019 by Kailash Singh

0 Comment     2138 Views    

In this tutorial, we are going to learn about how to Import excel (.csv) data into database using PHP.


Step 1 :- Create tables in Database.


In this step, we are going to create table in database.


CREATE TABLE `codingmantra`.`excel_detail` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(200) NOT NULL , `phone` VARCHAR(50) NOT NULL , `email` VARCHAR(200) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;


Step 2 :- Create .csv file.



Step 3 :- Save as .csv format.



Step 4 :- Create design to upload file.


<!doctype html>
      <link rel="stylesheet" href="">
      <script src=""></script>
      <script src=""></script>
      <script src=""></script>
        <div class="container">
          <div class="row" align="center" style="margin-top: 70px;">
              <div class="col-sm-3"></div>
              <div class="col-sm-6">
                    <h2>Import excel data into database using PHP</h2><br>

                    <!-- Success message print here -->
                    <?php echo $msg; ?>

                    <form method="post" action="" enctype='multipart/form-data'>
                        <input type='file' name='file' class="form-control" /><br>
                        <input type='submit' class="btn btn-primary" value='Upload Data' name='import'>
              <div class="col-sm-3"></div>


Step 5 : Create PHP Code to import data form the csv file.


// connection of database
 $con = mysqli_connect('localhost','root','','codingmantra');

$msg = '';


    $filename = $_FILES["file"]["tmp_name"];

    if($_FILES["file"]["size"] > 0)
        $file = fopen($filename, "r");

        while (($col = fgetcsv($file, 10000, ",")) !== FALSE) 
           // echo'<pre>'; print_r($col);

            $insert = "INSERT INTO excel_detail (name,phone,email)values('".$col[0]."','".$col[1]."','".$col[2]."')";

        $msg = '<p style="color: green;"> CSV Data inserted successfully</p>';





Hope this will help our developers.

Because we believe Mantra means CodingMantra

Comments ( 0 )