MNB PHPExcelDeveloper Guide
v2.0.5
Database module

Database Connections and Row Imports

Resolve PDO connections, import associative rows in batches, map columns, and configure duplicate behavior without coupling to a spreadsheet format.

Updated

LevelIntermediateReading time9 minPackagemnb/mnb-phpexcel
DatabaseConnectionFactory::make()SqlImporter::importRows()

What you will learn

  • Create a PDO connection from an object, DSN, array, .env, or config file.
  • Insert associative rows in batches using prepared statements.
  • Configure duplicate skip or update behavior for supported PDO drivers.

Create or reuse a PDO connection#

PHP
use Mnb\PHPExcel\Support\DatabaseConnectionFactory;

$pdo = DatabaseConnectionFactory::make([
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'database' => 'app',
    'username' => 'app_user',
    'password' => getenv('DB_PASSWORD'),
]);

You may pass an existing PDO, a DSN string, a config array, a PHP config path, an .env path, or null to resolve runtime environment values.

Insert rows in batches#

PHP
use Mnb\PHPExcel\Import\SqlImporter;

$result = (new SqlImporter())->importRows(
    $pdo,
    'products',
    $rows,
    [
        'batch_size' => 500,
        'duplicate_strategy' => 'update',
        'unique_by' => ['sku'],
        'skip_invalid_rows' => true,
    ]
);

Map source keys to database columns#

PHP
$result = (new SqlImporter())->importRows($pdo, 'customers', $rows, [
    'map' => [
        'Customer ID' => 'customer_id',
        'Full Name' => 'name',
        'Email Address' => 'email',
    ],
    'dry_run' => true,
]);