Skip to content

Instantly share code, notes, and snippets.

@ricardo-melo-martins
Last active February 21, 2024 15:50
Show Gist options
  • Save ricardo-melo-martins/1b5694521149d5a602838a5e3a0c793b to your computer and use it in GitHub Desktop.
Save ricardo-melo-martins/1b5694521149d5a602838a5e3a0c793b to your computer and use it in GitHub Desktop.
Php PDO mysql connect
// docker sakila database example in github.com/ricardo-melo-martins/docker

$config = [
    'type'=>'mysql',
    'hostname'=>'localhost',
    'database'=>'sakila',
    'username'=>'sakila',
    'password'=>'sakila'
];

try {
    $dsn = "mysql:host={$config['hostname']};dbname={$config['database']}";

    $connect = fn () => new \PDO(
        $dsn,
        $config['username'],
        $config['password'],
        [
            \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_BOTH,
        ]
    );

    $connection = $connect();
    
} catch(\PDOException $e){
    print($e);
    exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment