All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Import Excel File Into MySQL Using PHP

Last Updated : Jul 1, 2023

IN - PHP MySQL | Written & Updated By - Riya

In this tutorial we will show you how to import excel file data into mysql database using PHP. Generally this process is very hard if you directly import excel file data into mysql database but now by converting excel file into a csv(comma separated value) file then import data into mysql database.

This becomes easy and time saving here in this tutorial we will follow this step.

Import Excel File Into MySQL Using PHP

To Import Excel File Into MySQL It Takes Only Two Steps:-

  1. Make a HTML file and define markup
  2. Make a PHP file to import data into mysql database

Step 1. Make a HTML file and define markup

We make a HTML file and save it with a name import.html

<html>
<body>
<div id="wrapper">
 <form method="post" action="import_file.php" enctype="multipart/form-data">
  <input type="file" name="file"/>
  <input type="submit" name="submit_file" value="Submit"/>
 </form>
</div>
</body>
</html>

In this step we create a form to send csv file to 'import_file.php' page after manually converting from excel file.

Step 2. Make a PHP file to import data into mysql database

We make a PHP file and save it with a name import_file.php

// Database Structure 
CREATE TABLE 'employee' (
 'name' text NOT NULL,
 'age' text NOT NULL,
 'country' text NOT NULL,
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1

<?php
if(isset($_POST["submit_file"]))
{
 $file = $_FILES["file"]["tmp_name"];
 $file_open = fopen($file,"r");
 while(($csv = fgetcsv($file_open, 1000, ",")) !== false)
 {
  $name = $csv[0];
  $age = $csv[1];
  $country = $csv[2];
  mysql_query("INSERT INTO employee VALUES ('$name','$age','country')");
 }
}
?>

In this step we create a database 'employee' to store employee details which is stored in csv file.

We get the file and we use fopen to read the csv file and then we use fgetcsv function in while loop to get comma seperated value one by one and insert in database.

That's all, this is how to import excel file data into mysql database using PHP. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

I hope this tutorial on how to import xlsx file into mysql database using php helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Riya

A recent graduate with a Bachelor of Technology (B.Tech) in Computer Science from India. She is passionate about leveraging technology to solve real-world problems. With a strong foundation and experience in programming languages such as Python, Django, HTML, CSS, and JavaScript, java, php and have honed her skills through hands-on projects and coursework.

Follow Riya On Linkedin 🡪