A connection takes a DSN (data source name), a user, a password and an array of attributes. The DSN is the driver name, a colon, and key=value pairs separated by semicolons: host, port, dbname, charset and unix_socket for MySQL 524 . Every later example loads this file, which keeps the settings in one place and the password in the environment rather than in source control:
<?php
// db.php: the connection every example in this section starts from
return PDO::connect(
'mysql:host=localhost;dbname=shop;charset=utf8mb4',
'shop_app',
getenv('SHOP_DB_PASSWORD'),
[PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false],
);FETCH_ASSOC replaces the default FETCH_BOTH, which returns every column twice, under a number and a name. Turning off ATTR_EMULATE_PREPARES makes MySQL prepare statements itself (Subsection 4.16.6). The error mode needs no setting because exceptions are the default since PHP 8.0, and charset=utf8mb4 fixes the connection character set (Subsection 4.16.13). PDO::connect(), new in PHP 8.4, returns the driver subclass Pdo\Mysql (Subsection 4.16.14). Open one connection per request and pass it to the code that needs it (Subsection 4.9.15).