Database backup and restore is the most important part of maintaining software. Taking automatic periodical backup is a must for any project.
In case of unknown security flaws which may collapse your system. In such an unfortunate situation, it will be the holy grail to save you if you have a backup.
It is not only enough to take a backup by exporting your database. Also, we need to experiment with importing backups to ensure the restoration.
Backup files can be in any format. Many of the database clients support SQL, Excel or CSV format files to import external data.
We will create our own PHP database client only for importing Excel data into a database.
Restoring Excel backup into a database via programming will save us time. Let us study how to implement a quick restore by importing bulk data from Excel files. You may visit my earlier export data in CSV format if you want an export example.
This screenshot shows the output by displaying the list of imported rows from the database.
This example allows users to choose the import template via HTML form input. A sample Excel template is added with this downloadable resource.
With a valid file, the HTML form submitted will call PHP to process Excel parsing.
In PHP, the PHPSpreadsheet library is used to read the Excel file data and convert it into an array.
The code will execute the database insert row by row by iterating the array data.
See the Excel import example’s file structure shown below. The vendor folder has the PHPSpreadsheet library and its dependencies.
I have given a sample import template with these files to experiment with the import operation.
The schema.sql has the script to create the target database. You can find the SQL script in the next section.
Import the following SQL script and create a database environment. Also, configure your database details in DataSource.php to make this example work.
--
-- Database: `import_excel`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_info`
--
CREATE TABLE `tbl_info` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`description` varchar(50) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
--
-- Indexes for table `tbl_info`
--
ALTER TABLE `tbl_info`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for table `tbl_info`
--
ALTER TABLE `tbl_info`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;;
This HTML form with the file upload option is used to choose the Excel source. On submitting this form, the Excel file will be sent to the PHP to parse the data source. This file upload option will only allow the Excel files to choose using the accept attribute.
This code also contains the response HTML for displaying the message returned from PHP. This message is shown based on the type of response sent from PHP after Excel import.
<h2>Import Excel File into MySQL Database using PHP</h2>
<div class="outer-container">
<div class="row">
<form class="form-horizontal" action="" method="post"
name="frmExcelImport" id="frmExcelImport"
enctype="multipart/form-data" onsubmit="return validateFile()">
<div Class="input-row">
<label>Choose your file. <a href="Template/import-template.xlsx"
download>Download excel template</a></label>
<div>
<input type="file" name="file" id="file" class="file"
accept=".xls,.xlsx">
</div>
<div class="import">
<button type="submit" id="submit" name="import" class="btn-submit">Import
Excel and Save Data</button>
</div>
</div>
</form>
</div>
</div>
<div id="response"
class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
<?php
$sqlSelect = "SELECT * FROM tbl_info";
$result = $db->select($sqlSelect);
if (! empty($result)) {
?>
<table class='tutorial-table'>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<?php
foreach ($result as $row) { // ($row = mysqli_fetch_array($result))
?>
<tbody>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['description']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
In this PHP code, I specified the array of allowed file types for the file-type validation in PHP. I validated the uploaded file type along with the array allowed type.
If a match is found, the code will execute other logic. Otherwise, it will return the error message to the user.
With successful validation, excel file parsing read and convert the data into an array. Each array index has an array of row data. After reading the non-empty row data, I ran the database insert and showed the response.
<?php
use Phppot\DataSource;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
require_once 'DataSource.php';
$db = new DataSource();
$conn = $db->getConnection();
require_once ('vendor/autoload.php');
if (isset($_POST["import"])) {
$allowedFileType = [
'application/vnd.ms-excel',
'text/xls',
'text/xlsx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
if (in_array($_FILES["file"]["type"], $allowedFileType)) {
$targetPath = 'uploads/' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadSheet = $Reader->load($targetPath);
$excelSheet = $spreadSheet->getActiveSheet();
$spreadSheetAry = $excelSheet->toArray();
$sheetCount = count($spreadSheetAry);
for ($i = 1; $i <= $sheetCount; $i ++) {
$name = "";
if (isset($spreadSheetAry[$i][0])) {
$name = mysqli_real_escape_string($conn, $spreadSheetAry[$i][0]);
}
$description = "";
if (isset($spreadSheetAry[$i][1])) {
$description = mysqli_real_escape_string($conn, $spreadSheetAry[$i][1]);
}
if (! empty($name) || ! empty($description)) {
$query = "insert into tbl_info(name,description) values(?,?)";
$paramType = "ss";
$paramArray = array(
$name,
$description
);
$insertId = $db->insert($query, $paramType, $paramArray);
// $query = "insert into tbl_info(name,description) values('" . $name . "','" . $description . "')";
// $result = mysqli_query($conn, $query);
if (! empty($insertId)) {
$type = "success";
$message = "Excel Data Imported into the Database";
} else {
$type = "error";
$message = "Problem in Importing Excel Data";
}
}
}
} else {
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
?>
Note: Download the PHPSpreadsheet and include it in the vendor directory.
Nice one …this really solved my problem..
thanks vincy
Welcome Uzor. Happy it has helped you.
Why i can’t insert more than two rows?? I have 5rows only two get inserted
Hi Gebo,
This code is working for thousands of records. There should be something wrong in your input file. Do you get any errors?
thankyou, great idea
great tutorial, thanks alot
Welcome Umar.
Whats vendor, whats upload folder? you didn’t provide us with the most relevant information!
In the vendor folder you need to download the dependent and library and put it.
Is it possible for merged row in excel file
everything perfect thanks! how do i select only the first sheet? Thanks a lot!
In the custom loop, just skip the first record. A simple if-condition would suffice.
Superb tutorial Vincy , thanks
Welcome Sanjay.
good!….u save my day
Welcome! Keep rocking!
This really helpful to me thank you
Welcome Pedro.
Thank You …………mam
Welcome Vikram.
but this technique doesnot work if you have to import exel files to database and bring them in web pages as a link
Hi Rajan,
What is the issue you are facing?
Really Good Vincy, It’s Working Perfect .
Thanks :) Keeo Going On .
Welcome Gaurav.
Thank you, it really worked.
My only problem is; How I would import a workbook with two or more worksheets please.
I remain thanks
Hi Anderson,
Need to enhance the code for reading multiple worksheets. I will post an article soon on it.
thank you. what should i do if i want to start at the 2nd row since the 1st row is for title such as name, description etc.
Hi Don,
You need to make a minor change in the code. Declare a counter outside the loop and use that counter to skip the record of your choice.
Hi there,
You have saved me a lot of time
Thank you Panagiotis! Keep reading and sharing :-)
Hello, I keep having this error: XMLReader::open(): Unable to open source data.
Is there anything I can do for this to be fixed?
Hi Saber,
This error is related to file path and you need to resolve that.
Great Tutorial! Learnt a lot. Thank you.
Welcome Rick.
It’s fantastic work,it helps me…Big Thanks
Thank you Tesfaye. Welcome.
You deserve an accolade. Thanks for making my day
Welcome Samuel.
Work perfectly.
Thank you Joe.
Fatal error: Uncaught Error: Class ‘vendor\PhpOffice\PhpSpreadsheet\Reader\Xlsx’ not found in C:\xampp\htdocs\neco\index.php:24 Stack trace: #0 {main} thrown in C:\xampp\htdocs\neco\index.php on line 24 keep getting this error while trying to import
figured it out.
however is there a way to check against duplicate records in the excel while importing??
Hi Samuel,
You need to include the vendor files.
Uncaught Error: Class ‘PhpOffice\PhpSpreadsheet\Reader\Xlsx’ not found.
Hi, I am facing this error, can you please help me with this.
Hi Hritika,
You need to include the vendor files.
Thank so much Vincy.. keep posting
Welcome Vimalraj.
I have a unique case here. How do I upload my excel sheet on two databases runing on separate server via Application Programming Interface (API) call? In addition, I want the a situation where if data stored in database A is updated, the changes should be reflected in database B.
Kindly help post something on this. Thanking you always….
Yes. PHP cURL post with an API call can handle your situation.
Sure. I will post an example code in this soon.
Thank you for reading.
the vendor folder is empty why?
You can downloaded the dependency and put it in the vendor folder. Its easy.