Hellow Reader's ! In This Blog we are going to import excel file into MySql table using PHP. If you have Excel files that need to be imported into MySQL, you can import them easily with PHP. First you need to download Excel reader File. In this blog i am using php-excel-reader its is very simple and easy to use.
First Create database and table;
Create DataBase:-info
Table: user_info
CREATE TABLE `user_info` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT,
`eid` VARCHAR( 100 ) NOT NULL ,
`name` VARCHAR( 200 ) NOT NULL ,
`email` VARCHAR( 200 ) NOT NULL ,
`dob` datetime not null,
PRIMARY KEY (id)
);
Note:-You can get "excel_reader2.php" below this code and place this file in same directory.
Note:-You can get "example.xls" below this code and place this file in same directory.
index.php
Contains HTML and PHP include library and insert records in database.
<?php
ini_set("display_errors",1);
require_once 'excel_reader2.php';
$connection=new mysqli('localhost','db_name','db_password','info');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tabledata=mysqli_query($connection,"select * from user_info"); //Retrieve Data from table
$data = new Spreadsheet_Excel_Reader("example.xls"); //load xls file into excel library
echo "Total Sheets in this xls file: ".count($data->sheets)."<br /><br />";
$html="<table border='1'>";
for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
{
if(count($data->sheets[$i]['cells'])>0) // checking sheet not empty
{
echo "Sheet $i:<br /><br />Total rows in sheet $i ".count($data->sheets[$i]['cells'])."<br />";
for($j=1;$j<=count($data->sheets[$i]['cells']);$j++) // loop used to get each row of the sheet
{
$html.="<tr>";
for($k=1;$k<=count($data->sheets[$i]['cells'][$j]);$k++) // This loop is created to get data in a table format.
{
$html.="<td>";
$html.=$data->sheets[$i]['cells'][$j][$k];
$html.="</td>";
}
$data->sheets[$i]['cells'][$j][1];
$eid = mysqli_real_escape_string($connection,$data->sheets[$i]['cells'][$j][1]);
$name = mysqli_real_escape_string($connection,$data->sheets[$i]['cells'][$j][2]);
$email = mysqli_real_escape_string($connection,$data->sheets[$i]['cells'][$j][3]);
$dob = mysqli_real_escape_string($connection,$data->sheets[$i]['cells'][$j][4]);
$query = "insert into user_info(eid,name,email,dob) values('".$eid."','".$name."','".$email."','".$dob."')";
mysqli_query($connection,$query);
$html.="</tr>";
}
}
}
$html.="</table>";
echo $html;
echo "<br />Data Inserted in dababase<br />";
while($row=mysqli_fetch_array($tabledata))
{
echo "</br> ".$row['name']." ".$row['email']." ".$row['dob']." </br>";
}
?>
Hope this will be helpful for you!!! Contact me if there is any problem :)
5 Comment(s)