Skip to content
MNB PHPExcelDeveloper Guide
AI

Database library

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.

Level
Intermediate
Reading time
9 min
Package
mnb/mnb-phpexcel-database
Updated
DatabaseConnectionFactory::make()SqlImporter::importRows()

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,
]);