PDO connecting to MySQL/MariaDB server
suggest changeThere are two ways to connect to a MySQL/MariaDB server, depending on your infrastructure.
Standard (TCP/IP) connection
$dsn = 'mysql:dbname=demo;host=server;port=3306;charset=utf8';
$connection = new \PDO($dsn, $username, $password);
// throw exceptions, when SQL error is caused
$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
// prevent emulation of prepared statements
$connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
Since PDO was designed to be compatible with older MySQL server versions (which did not have support for prepared statements), you have to explicitly disable the emulation. With emulation on, PDO still escapes bound strings, but a mismatched connection charset can defeat that escaping. MySQL's utf8 charset is three bytes per character; utf8mb4 covers the rest of Unicode.
Another design compromise is the default error handling behavior. Before PHP 8.0, PDO stayed silent unless you changed the error mode. Since PHP 8.0 the default is PDO::ERRMODE_EXCEPTION.
Set exception mode explicitly when you want a UNIQUE violation to arrive as an exception you can catch.
Socket connection
$dsn = 'mysql:unix_socket=/tmp/mysql.sock;dbname=demo;charset=utf8';
$connection = new \PDO($dsn, $username, $password);
// throw exceptions, when SQL error is caused
$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
// prevent emulation of prepared statements
$connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
On unix-like systems, if host name is 'localhost', then the connection to the server is made through a domain socket.