Import Excel into a Database
Validate an uploaded workbook, inspect and select its worksheet, confirm headers, preview rows, and import records through PDO with clear failure handling.
Updated
MnbExcel::validateUpload()MnbExcel::read()ReadSession::dryRunImportToSql()ReadSession::importToSql()What you will learn
- Reject unsafe or unsupported uploads before parsing.
- Verify the worksheet and required columns before database changes.
- Preview and then execute an import with a stable business key.
Use the production-safe recipe#
The complete implementation is maintained on a dedicated page because upload security, private storage, workbook validation, header checks, dry runs, transactions, and public error responses must stay together.
Import workflow at a glance#
- Validate the HTTP upload
Allow only expected extensions, enforce file and package limits, and reject invalid packages.
- Move to private storage
Generate the storage name in the application and keep it outside the public web root.
- Inspect and select the worksheet
List sheets, select the required sheet, and reject unexpected layouts.
- Confirm required headers
Read one normalized row and compare its keys with the import contract.
- Dry-run the database mapping
Review inserts, updates, invalid rows, duplicate behavior, and totals before changing data.
- Import transactionally
Use batches, unique indexes, safe duplicate strategy, and server-side error logs.
Developer contract#
- Upload validation result
arraywith avalidflag and validation context.- Dry-run result
arraydescribing the planned import without changing rows.- Import result
arraysummary for inserted, updated, skipped, and failed rows.- Database boundary
- PDO connection with exceptions enabled and a unique index for business keys.
- Public response
- A safe user message; full debug context remains in server logs.
- Errors
MnbExcelException, upload validation errors, PDO exceptions, or application contract errors.
Array
(
[inserted] => 1720
[updated] => 85
[skipped] => 2
[failed] => 4
)Exact result keys depend on the selected importer options and duplicate strategy.
Continue the workflow#
Use one complete boundary example from HTTP upload to transactional PDO import.
→DATABASEDatabase import optionsConfigure maps, batches, duplicates, dry runs, and SQL constraints.
→VALIDATIONTemplates and validationGenerate templates, preview uploaded rows, validate values, and report duplicates.
→