Initialization

How to connect PDOdb to your database.

Basic connection

Pass your database credentials as an array to the constructor:

$db = new PDOdb([
    'host'     => 'localhost',
    'username' => 'your_user',
    'password' => 'your_password',
    'db'       => 'your_database',
    'charset'  => 'utf8mb4',
]);

All parameters

Parameter Type Default Description
host string null Database host, e.g. 'localhost' or an IP address
username string null Database user
password string null Database password
db string null Database name
port int 3306 MySQL port – only needed if your server uses a non-standard port
charset string 'utf8mb4' Connection charset – utf8mb4 is recommended for full Unicode support including emojis
socket string null Unix socket path – use instead of host when connecting via socket
prefix string '' Table prefix – automatically prepended to all table names in queries
instance string 'default' Instance name – used to manage multiple connections side by side

With table prefix

If your tables use a prefix (e.g. WordPress-style wp_), pass it once during initialization. PDOdb will automatically prepend it to every table name in all queries.

$db = new PDOdb([
    'host'     => 'localhost',
    'username' => 'your_user',
    'password' => 'your_password',
    'db'       => 'your_database',
    'prefix'   => 'wp_',
]);

$users = $db->get('users');
// → SELECT * FROM wp_users

You can also set or change the prefix at any time after initialization:

$db->setPrefix('app_');

$users = $db->get('users');
// → SELECT * FROM app_users

Unix socket connection

If your MySQL server is running on the same machine, connecting via Unix socket is faster than TCP/IP. Use socket instead of host:

$db = new PDOdb([
    'socket'   => '/var/run/mysqld/mysqld.sock',
    'username' => 'your_user',
    'password' => 'your_password',
    'db'       => 'your_database',
]);

Access the instance globally

Once initialized, you can retrieve the connection from anywhere in your application using the static getInstance() method – no need to pass $db around.

// Initialize once (e.g. in bootstrap.php)
$db = new PDOdb([
    'host'     => 'localhost',
    'username' => 'your_user',
    'password' => 'your_password',
    'db'       => 'your_database',
]);

// Retrieve anywhere else in your code
$db = PDOdb::getInstance();

// Step by step
$db->whereInt('active', 1);
$users = $db->get('users');

// Fluent
$users = PDOdb::getInstance()
              ->whereInt('active', 1)
              ->get('users');

// → SELECT * FROM users WHERE active = 1
getInstance() returns null if no connection has been created yet. Always initialize PDOdb before calling it.

See also