Search code examples
phpmysqlsqlpdomariadb

PDO Connection string: What is the best way to do it?


i want to make an backend application using php/pdo. I have found a lot different ways to do PDO connection strings. I was wondering, what is the best way to do a connection string using pdo. Is this the best way of doing a connection string or should i use some other code. Any suggestions or adjustments are welcome!

This is what i have at the moment:

<?php

$host = "localhost";
$db = "phpcrud";
$username = "root";
$password = "";

$conn = new PDO("mysql:host=$host;dbname=$db;charset=UTF8", $username, $password, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]);

?>

Solution

  • This question is not as easy as it seems. I wrote a canonical example, How to connect to MySQL using PDO.

    So let's see what can be improved here:

    • charset could be set to utf8mb4 (which is now a recommended standard for MySQL as it supports the full set of UTF-8 characters, whereas utf8 is only a limited subset)
    • emulation mode is better to be turned off (for convenience and some would say better security)
    • The PDO class name is better to be prefixed with a global namespace, so the code would be able to work in a namespaced environment.

    So here you go:

    $options = [
        \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
        \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
        \PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $pdo = new \PDO($dsn, $username, $password, $options);