Database connection configuration for MySQL, MariaDB, PostgreSQL, SQLite, Microsoft SQL Server (MSSQL), and Oracle Database.
use tommyknocker\pdodb\PdoDb;
$db = new PdoDb('mysql', [
'host' => '127.0.0.1',
'username' => 'testuser',
'password' => 'testpass',
'dbname' => 'testdb'
]);$db = new PdoDb('mysql', [
// Connection options
'pdo' => null, // Optional: Existing PDO object
'host' => '127.0.0.1', // Required: MySQL host
'username' => 'testuser', // Required: MySQL username
'password' => 'testpass', // Required: MySQL password
'dbname' => 'testdb', // Required: Database name
'port' => 3306, // Optional: MySQL port (default: 3306)
'prefix' => 'my_', // Optional: Table prefix (e.g. 'wp_')
'charset' => 'utf8mb4', // Optional: Connection charset
// Advanced options
'unix_socket' => '/var/run/mysqld/mysqld.sock', // Optional: Unix socket path
'sslca' => '/path/ca.pem', // Optional: SSL CA certificate
'sslcert' => '/path/client-cert.pem', // Optional: SSL client certificate
'sslkey' => '/path/client-key.pem', // Optional: SSL client key
'compress' => true // Optional: Enable protocol compression
]);$pdo = new PDO(
'mysql:host=localhost;dbname=testdb',
'user',
'pass'
);
$db = new PdoDb('mysql', [
'pdo' => $pdo,
'prefix' => 'wp_'
]);MariaDB uses the same driver as MySQL ('mysql') and shares the same configuration options. MariaDB is fully supported as a separate dialect with optimized SQL generation.
use tommyknocker\pdodb\PdoDb;
$db = new PdoDb('mysql', [
'host' => '127.0.0.1',
'username' => 'testuser',
'password' => 'testpass',
'dbname' => 'testdb'
]);$db = new PdoDb('mysql', [
// Connection options
'pdo' => null, // Optional: Existing PDO object
'host' => '127.0.0.1', // Required: MariaDB host
'username' => 'testuser', // Required: MariaDB username
'password' => 'testpass', // Required: MariaDB password
'dbname' => 'testdb', // Required: Database name
'port' => 3306, // Optional: MariaDB port (default: 3306)
'prefix' => 'my_', // Optional: Table prefix (e.g. 'wp_')
'charset' => 'utf8mb4', // Optional: Connection charset
// Advanced options
'unix_socket' => '/var/run/mysqld/mysqld.sock', // Optional: Unix socket path
'sslca' => '/path/ca.pem', // Optional: SSL CA certificate
'sslcert' => '/path/client-cert.pem', // Optional: SSL client certificate
'sslkey' => '/path/client-key.pem', // Optional: SSL client key
'compress' => true // Optional: Enable protocol compression
]);$pdo = new PDO(
'mysql:host=localhost;dbname=testdb',
'user',
'pass'
);
$db = new PdoDb('mysql', [
'pdo' => $pdo,
'prefix' => 'app_'
]);Note: MariaDB uses the same driver name ('mysql') as MySQL, but PDOdb automatically detects MariaDB and uses the MariaDB dialect for optimized SQL generation.
use tommyknocker\pdodb\PdoDb;
$db = new PdoDb('pgsql', [
'host' => '127.0.0.1',
'username' => 'testuser',
'password' => 'testpass',
'dbname' => 'testdb'
]);$db = new PdoDb('pgsql', [
// Connection options
'pdo' => null, // Optional: Existing PDO object
'host' => '127.0.0.1', // Required: PostgreSQL host
'username' => 'testuser', // Required: PostgreSQL username
'password' => 'testpass', // Required: PostgreSQL password
'dbname' => 'testdb', // Required: Database name
'port' => 5432, // Optional: PostgreSQL port (default: 5432)
'prefix' => 'pg_', // Optional: Table prefix
// Advanced options
'options' => '--client_encoding=UTF8', // Optional: Extra options
'sslmode' => 'require', // Optional: SSL mode (disable, allow, prefer, require, verify-ca, verify-full)
'sslkey' => '/path/client.key', // Optional: SSL private key
'sslcert' => '/path/client.crt', // Optional: SSL client certificate
'sslrootcert' => '/path/ca.crt', // Optional: SSL root certificate
'application_name' => 'MyApp', // Optional: Application name (visible in pg_stat_activity)
'connect_timeout' => 5, // Optional: Connection timeout in seconds
'hostaddr' => '192.168.1.10', // Optional: Direct IP address (bypasses DNS)
'service' => 'myservice', // Optional: Service name from pg_service.conf
'target_session_attrs' => 'read-write' // Optional: For clusters (any, read-write)
]);use tommyknocker\pdodb\PdoDb;
// In-memory database
$db = new PdoDb('sqlite', [
'path' => ':memory:'
]);
// File-based database
$db = new PdoDb('sqlite', [
'path' => '/path/to/database.sqlite'
]);$db = new PdoDb('sqlite', [
// Connection options
'pdo' => null, // Optional: Existing PDO object
'path' => '/path/to/database.sqlite', // Required: Path to SQLite file
// Use ':memory:' for in-memory database
'prefix' => 'sq_', // Optional: Table prefix
'mode' => 'rwc', // Optional: Open mode (ro, rw, rwc, memory)
'cache' => 'shared', // Optional: Cache mode (shared, private)
'enable_regexp' => true // Optional: Enable REGEXP functions (default: true)
// Automatically registers REGEXP, regexp_replace, regexp_extract
]);ro- Read-only accessrw- Read/write accessrwc- Read/write/create if not exists (default)memory- In-memory database
You can pass additional PDO options when creating a connection:
use tommyknocker\pdodb\PdoDb;
$pdoOptions = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$db = new PdoDb('mysql', [
'host' => 'localhost',
'username' => 'user',
'password' => 'pass',
'dbname' => 'testdb'
], $pdoOptions);$pdoOptions = [
// Error handling
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// Fetch mode
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
// Disable emulated prepares for better performance and security
PDO::ATTR_EMULATE_PREPARES => false,
// Use persistent connections (optional, be careful with this)
// PDO::ATTR_PERSISTENT => true,
// Connection timeout (MySQL only)
// PDO::ATTR_TIMEOUT => 5
];
$db = new PdoDb('mysql', $config, $pdoOptions);Enable automatic prepared statement caching for better performance:
use tommyknocker\pdodb\PdoDb;
$db = new PdoDb('mysql', [
'host' => 'localhost',
'username' => 'user',
'password' => 'pass',
'dbname' => 'mydb',
'stmt_pool' => [
'enabled' => true, // Enable statement pooling
'capacity' => 256 // Maximum cached statements (default: 256)
]
]);See: Connection Management - Prepared Statement Pool for detailed documentation.
You can manage multiple database connections:
use tommyknocker\pdodb\PdoDb;
// Initialize without a default connection
$db = new PdoDb();
// Add MySQL connection
$db->addConnection('mysql_main', [
'driver' => 'mysql',
'host' => 'mysql.server.com',
'username' => 'user',
'password' => 'pass',
'dbname' => 'main_db'
]);
// Add PostgreSQL connection
$db->addConnection('pgsql_analytics', [
'driver' => 'pgsql',
'host' => 'postgres.server.com',
'username' => 'analyst',
'password' => 'pass',
'dbname' => 'analytics'
]);
// Switch between connections
$users = $db->connection('mysql_main')->find()->from('users')->get();
$stats = $db->connection('pgsql_analytics')->find()->from('stats')->get();PDOdb supports loading configuration from .env files using the PdoDb::fromEnv() static method. This provides a convenient way to manage database configuration without hardcoding credentials.
Create a .env file in your project root:
PDODB_DRIVER=mysql
PDODB_HOST=localhost
PDODB_PORT=3306
PDODB_DATABASE=testdb
PDODB_USERNAME=testuser
PDODB_PASSWORD=testpass
PDODB_CHARSET=utf8mb4Then load the configuration:
use tommyknocker\pdodb\PdoDb;
// Load from .env file in current directory
$db = PdoDb::fromEnv();
// Or specify a custom .env file path
$db = PdoDb::fromEnv('/path/to/.env.local');The following environment variables are supported in .env files:
| Variable | Required | Description | Example |
|---|---|---|---|
PDODB_DRIVER |
Yes | Database driver name | mysql, pgsql, sqlite, sqlsrv, oci |
PDODB_HOST |
Yes* | Database host | localhost, 127.0.0.1 |
PDODB_PORT |
No | Database port | 3306, 5432, 1433, 1521 |
PDODB_DATABASE |
Yes* | Database name | testdb, mydb |
PDODB_USERNAME |
Yes* | Database username | testuser, root |
PDODB_PASSWORD |
No | Database password | secret123 |
PDODB_CHARSET |
No | Connection charset | utf8mb4, UTF8 |
PDODB_PATH |
Yes* | SQLite database path | :memory:, /path/to/db.sqlite |
* Required for most databases, except SQLite which only requires PDODB_DRIVER and PDODB_PATH.
The .env file supports:
- Key-value pairs:
KEY=value - Comments: Lines starting with
#are ignored - Quoted values: Both single and double quotes are supported and automatically removed
- Empty lines: Ignored
Example .env file:
# Database Configuration
PDODB_DRIVER=mysql
PDODB_HOST=localhost
PDODB_PORT=3306
PDODB_DATABASE=testdb
# Credentials
PDODB_USERNAME=testuser
PDODB_PASSWORD="secret123"
PDODB_CHARSET=utf8mb4You can specify a custom path to the .env file:
$db = PdoDb::fromEnv('/path/to/.env.production');Or set the PDODB_ENV_PATH environment variable:
export PDODB_ENV_PATH=/path/to/.env.production
php your-script.phpYou can pass additional options to fromEnv():
use Psr\Log\NullLogger;
use tommyknocker\pdodb\cache\CacheFactory;
$pdoOptions = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$logger = new NullLogger();
$cache = CacheFactory::create(['type' => 'array', 'enabled' => true]);
$db = PdoDb::fromEnv(
null, // Use default .env path
$pdoOptions, // PDO options
$logger, // Logger instance
$cache // Cache instance
);If PDODB_DRIVER is not set in the .env file, fromEnv() will throw an InvalidArgumentException:
try {
$db = PdoDb::fromEnv();
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
// Error: PDODB_DRIVER not set in .env file
}For non-SQLite databases, if required variables (PDODB_DATABASE, PDODB_USERNAME) are missing, an exception will be thrown:
try {
$db = PdoDb::fromEnv();
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
// Error: PDODB_DATABASE and PDODB_USERNAME must be set in .env file for driver: mysql
}You can also use environment variables directly without .env files:
// config.php
return [
'host' => getenv('DB_HOST') ?: 'localhost',
'username' => getenv('DB_USERNAME') ?: 'root',
'password' => getenv('DB_PASSWORD') ?: '',
'dbname' => getenv('DB_NAME') ?: 'testdb',
'charset' => getenv('DB_CHARSET') ?: 'utf8mb4'
];
// Usage
$db = new PdoDb('mysql', require 'config.php');$db = new PdoDb('mysql', [
'host' => 'mysql.example.com',
'username' => 'user',
'password' => 'pass',
'dbname' => 'mydb',
'sslcert' => '/path/to/client-cert.pem',
'sslkey' => '/path/to/client-key.pem',
'sslca' => '/path/to/ca.pem'
]);$db = new PdoDb('pgsql', [
'host' => 'postgres.example.com',
'username' => 'user',
'password' => 'pass',
'dbname' => 'mydb',
'sslmode' => 'require',
'sslcert' => '/path/to/client.crt',
'sslkey' => '/path/to/client.key',
'sslrootcert' => '/path/to/ca.crt'
]);use tommyknocker\pdodb\PdoDb;
$db = new PdoDb('sqlsrv', [
'host' => 'localhost',
'username' => 'testuser',
'password' => 'testpass',
'dbname' => 'testdb'
]);$db = new PdoDb('sqlsrv', [
// Connection options
'pdo' => null, // Optional: Existing PDO object
'host' => 'localhost', // Required: SQL Server host
'username' => 'testuser', // Required: SQL Server username
'password' => 'testpass', // Required: SQL Server password
'dbname' => 'testdb', // Required: Database name
'port' => 1433, // Optional: SQL Server port (default: 1433)
'prefix' => 'mssql_', // Optional: Table prefix
// SSL/TLS options
'trust_server_certificate' => true, // Optional: Trust server certificate (default: true)
// Set to false for production with valid certificates
'encrypt' => true, // Optional: Enable encryption (default: true)
]);$pdo = new PDO(
'sqlsrv:Server=localhost,1433;Database=testdb;TrustServerCertificate=yes;Encrypt=yes',
'user',
'pass'
);
$db = new PdoDb('sqlsrv', [
'pdo' => $pdo,
'prefix' => 'app_'
]);For self-signed certificates (development/testing):
$db = new PdoDb('sqlsrv', [
'host' => 'localhost',
'username' => 'user',
'password' => 'pass',
'dbname' => 'mydb',
'trust_server_certificate' => true, // Trust self-signed certificates
'encrypt' => true // Enable encryption
]);For production with valid certificates:
$db = new PdoDb('sqlsrv', [
'host' => 'sqlserver.example.com',
'username' => 'user',
'password' => 'pass',
'dbname' => 'mydb',
'trust_server_certificate' => false, // Require valid certificate
'encrypt' => true // Enable encryption
]);Note: MSSQL uses the sqlsrv driver name. The Microsoft ODBC Driver for SQL Server must be installed, and the PHP sqlsrv extension must be enabled.
use tommyknocker\pdodb\PdoDb;
$db = new PdoDb('oci', [
'host' => 'localhost',
'port' => 1521,
'username' => 'testuser',
'password' => 'testpass',
'service_name' => 'XEPDB1', // Oracle service name (or use 'sid' for SID)
'charset' => 'UTF8'
]);$db = new PdoDb('oci', [
// Connection options
'pdo' => null, // Optional: Existing PDO object
'host' => 'localhost', // Required: Oracle host
'port' => 1521, // Optional: Oracle port (default: 1521)
'username' => 'testuser', // Required: Oracle username
'password' => 'testpass', // Required: Oracle password
'service_name' => 'XEPDB1', // Required: Oracle service name (preferred)
// OR use 'sid' instead of 'service_name' for SID-based connections
'sid' => 'XE', // Optional: Oracle SID (alternative to service_name)
'dbname' => 'XEPDB1', // Optional: Fallback to dbname if service_name/sid not provided
'prefix' => 'app_', // Optional: Table prefix
'charset' => 'UTF8', // Optional: Connection charset (default: UTF8)
]);Oracle 12c+ uses service names for Pluggable Databases (PDBs):
$db = new PdoDb('oci', [
'host' => 'localhost',
'port' => 1521,
'username' => 'testuser',
'password' => 'testpass',
'service_name' => 'XEPDB1' // Pluggable Database service name
]);For older Oracle installations or non-CDB databases:
$db = new PdoDb('oci', [
'host' => 'localhost',
'port' => 1521,
'username' => 'testuser',
'password' => 'testpass',
'sid' => 'XE' // Oracle SID
]);$pdo = new PDO(
'oci:dbname=//localhost:1521/XEPDB1',
'user',
'pass'
);
$db = new PdoDb('oci', [
'pdo' => $pdo,
'prefix' => 'app_'
]);Oracle configuration via environment variables:
export PDODB_DRIVER=oci
export PDODB_HOST=localhost
export PDODB_PORT=1521
export PDODB_USERNAME=testuser
export PDODB_PASSWORD=testpass
export PDODB_SERVICE_NAME=XEPDB1
export PDODB_CHARSET=UTF8
export PDODB_PREFIX=app_Note: Oracle uses the oci driver name. The PHP pdo_oci extension must be installed and enabled. Oracle Database 12c+ is recommended for full feature support (JSON operations, LATERAL JOINs, etc.).
All database dialects support configuration via .env file or environment variables. The following variables are available:
| Variable | Description | Required | Default |
|---|---|---|---|
PDODB_DRIVER |
Database driver (mysql, mariadb, pgsql, sqlite, sqlsrv, oci) |
Yes | - |
PDODB_HOST |
Database host | Yes* | localhost |
PDODB_PORT |
Database port | No | Driver default |
PDODB_DATABASE |
Database name | Yes* | - |
PDODB_USERNAME |
Database username | Yes* | - |
PDODB_PASSWORD |
Database password | Yes* | - |
PDODB_CHARSET |
Connection charset | No | Driver default |
PDODB_PREFIX |
Table prefix | No | Empty |
* Not required for SQLite
| Variable | Description | Type | Default |
|---|---|---|---|
PDODB_UNIX_SOCKET |
Unix socket path | String | - |
PDODB_SSLCA |
SSL CA certificate path | String | - |
PDODB_SSLCERT |
SSL client certificate path | String | - |
PDODB_SSLKEY |
SSL client key path | String | - |
PDODB_COMPRESS |
Enable protocol compression | Boolean | false |
Example:
PDODB_DRIVER=mysql
PDODB_HOST=localhost
PDODB_DATABASE=mydb
PDODB_USERNAME=user
PDODB_PASSWORD=pass
PDODB_PREFIX=wp_
PDODB_UNIX_SOCKET=/var/run/mysqld/mysqld.sock
PDODB_SSLCA=/path/ca.pem
PDODB_SSLCERT=/path/client-cert.pem
PDODB_SSLKEY=/path/client-key.pem
PDODB_COMPRESS=true| Variable | Description | Type | Default |
|---|---|---|---|
PDODB_SSLMODE |
SSL mode (disable, allow, prefer, require, verify-ca, verify-full) |
String | - |
PDODB_SSLKEY |
SSL private key path | String | - |
PDODB_SSLCERT |
SSL client certificate path | String | - |
PDODB_SSLROOTCERT |
SSL root certificate path | String | - |
PDODB_APPLICATION_NAME |
Application name (visible in pg_stat_activity) |
String | - |
PDODB_CONNECT_TIMEOUT |
Connection timeout in seconds | Integer | - |
PDODB_HOSTADDR |
Direct IP address (bypasses DNS) | String | - |
PDODB_SERVICE |
Service name from pg_service.conf |
String | - |
PDODB_TARGET_SESSION_ATTRS |
Target session attributes (any, read-write) |
String | - |
PDODB_OPTIONS |
Extra connection options | String | - |
Example:
PDODB_DRIVER=pgsql
PDODB_HOST=localhost
PDODB_DATABASE=mydb
PDODB_USERNAME=user
PDODB_PASSWORD=pass
PDODB_PREFIX=app_
PDODB_SSLMODE=require
PDODB_SSLCERT=/path/client.crt
PDODB_SSLKEY=/path/client.key
PDODB_SSLROOTCERT=/path/ca.crt
PDODB_APPLICATION_NAME=MyApp
PDODB_CONNECT_TIMEOUT=5| Variable | Description | Type | Default |
|---|---|---|---|
PDODB_PATH |
Path to SQLite file (use :memory: for in-memory) |
String | ./database.sqlite |
PDODB_MODE |
Open mode (ro, rw, rwc, memory) |
String | rwc |
PDODB_CACHE |
Cache mode (shared, private) |
String | - |
PDODB_ENABLE_REGEXP |
Enable REGEXP functions | Boolean | true |
Example:
PDODB_DRIVER=sqlite
PDODB_PATH=:memory:
PDODB_PREFIX=test_
PDODB_MODE=rwc
PDODB_CACHE=shared
PDODB_ENABLE_REGEXP=true| Variable | Description | Type | Default |
|---|---|---|---|
PDODB_TRUST_SERVER_CERTIFICATE |
Trust server certificate | Boolean | true |
PDODB_ENCRYPT |
Enable encryption | Boolean | true |
Example:
PDODB_DRIVER=sqlsrv
PDODB_HOST=localhost
PDODB_DATABASE=mydb
PDODB_USERNAME=user
PDODB_PASSWORD=pass
PDODB_PREFIX=mssql_
PDODB_TRUST_SERVER_CERTIFICATE=true
PDODB_ENCRYPT=true| Variable | Description | Type | Default |
|---|---|---|---|
PDODB_SERVICE_NAME |
Oracle service name (preferred for 12c+) | String | - |
PDODB_SID |
Oracle SID (alternative to service_name) | String | - |
Note: Use PDODB_SERVICE_NAME for Oracle 12c+ Pluggable Databases (PDBs), or PDODB_SID for older installations.
Example:
PDODB_DRIVER=oci
PDODB_HOST=localhost
PDODB_PORT=1521
PDODB_USERNAME=testuser
PDODB_PASSWORD=testpass
PDODB_SERVICE_NAME=XEPDB1
PDODB_CHARSET=UTF8
PDODB_PREFIX=app_Create a .env file in your project root:
# .env
PDODB_DRIVER=mysql
PDODB_HOST=localhost
PDODB_DATABASE=mydb
PDODB_USERNAME=user
PDODB_PASSWORD=pass
PDODB_PREFIX=app_
PDODB_CHARSET=utf8mb4Then use PdoDb::fromEnv():
use tommyknocker\pdodb\PdoDb;
// Load from .env file in current directory
$db = PdoDb::fromEnv();
// Or specify custom path
$db = PdoDb::fromEnv('/path/to/.env.local');Boolean environment variables accept the following values:
true,1,yes,on→truefalse,0,no,off→false
Examples:
PDODB_COMPRESS=true
PDODB_ENABLE_REGEXP=1
PDODB_TRUST_SERVER_CERTIFICATE=yes
PDODB_ENCRYPT=false- First Connection - Make your first connection
- Hello World - Build your first query