Import an Excel file in MySql Database using php

welcome back to shortlearner.com, In this tutorial, we will see how to Import an Excel file in Mysql database. In the First step we will create a Database to insert an excel data into Mysql table, a form to make a view to upload an Excel Sheet and also create a PHP script to perform operation to insert data into Database.

Create Database

To Insert excel sheet data into MySql database, we need to create a database named as ‘test_excel’ and also create a table named as ‘excel_sheet’

Also Read :
How to Install PHP on CentOS.
How to integrate Razorpay Payment Gateway using PHP.

PHP Login Script With Remember me.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript
Check Email is Already Registered in Database using Ajax and JavaScript.
How to hide extension of html and php file.?

-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 13, 2017 at 01:51 PM
-- Server version: 10.1.25-MariaDB
-- PHP Version: 5.6.31

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `test_excel`
--

-- --------------------------------------------------------

--
-- Table structure for table `excel_sheet`
--

CREATE TABLE `excel_sheet` (
  `website` varchar(255) NOT NULL,
  `category` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


--

Config.php

after creating database , we move on the config.php page.. here we make a database connection.

<?php
function getdb(){
$servername = "localhost";
$username = "root";
$password = "";
$db = "test_excel";

try {
   
    $conn = mysqli_connect($servername, $username, $password, $db);
     //echo "Connected successfully"; 
    }
catch(exception $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
    return $conn;
}
?>

Index.php

after creating database , we move on the index page.. in the index page we take a csv file from our computer and redirect it to functions.php page . where we check that the file which is selected is CSV  or not.

<!DOCTYPE html>
<html lang="en">
 
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
 
</head>
 
<body>
    <div id="wrap">
        <div class="container">
            <div class="row">
 
                <form class="form-horizontal" action="functions.php" method="post" name="upload_excel" enctype="multipart/form-data">
                    <fieldset>
 
                        <!-- Form Name -->
                        <legend>Form Name</legend>
 
                        <!-- File Button -->
                        <div class="form-group">
                            <label class="col-md-4 control-label" for="filebutton">Select File</label>
                            <div class="col-md-4">
                                <input type="file" name="file" id="file" class="input-large">
                            </div>
                        </div>
 
                        <!-- Button -->
                        <div class="form-group">
                            <label class="col-md-4 control-label" for="singlebutton">Import data</label>
                            <div class="col-md-4">
                                <button type="submit" id="submit" name="Import" class="btn btn-primary button-loading" data-loading-text="Loading...">Import</button>
                            </div>
                        </div>
 
                    </fieldset>
                </form>
 
            </div>
           
        </div>
    </div>
</body>
 
</html>

functions.php

In this page we catch the file and check it , if our file is  csv than it import into database otherwise it shows the error and redirect to index.php page.

<?php


 if(isset($_POST["Import"])){
		
		$filename=$_FILES["file"]["tmp_name"];		


		 if($_FILES["file"]["size"] > 0)
		 {
		  	$file = fopen($filename, "r");
	        while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
	         {


	       echo     $sql = "INSERT into excel_sheet (website, category) 
                   values ('".$getData[0]."','".$getData[1]."')";
                   $result = mysqli_query($conn, $sql);
				if(!isset($result))
				{
					echo "<script type=\"text/javascript\">
							alert(\"Invalid File:Please Upload CSV File.\");
							window.location = \"index.php\"
						  </script>";		
				}
				else {
					  echo "<script type=\"text/javascript\">
						alert(\"CSV File has been successfully Imported.\");
						window.location = \"index.php\"
					</script>";
				}
	         }
			
	         fclose($file);	
		 }
	}	 


 ?>

Keep Learning..