Good question. Although the connection code itself is good, some improvements can be made.
A separate config file
When your code goes live, most likely database credentials will be different from those at home. Therefore, having them hardcoded in the script will make it extremely inconvenient. Instead, create a separate file for your configuration as follows:
add the config.php
line in .gitignore
(in case you are not using git yet, you definitely should)
create a file called config.sample.php
with all variables set to empty values like this:
return [
'db' => [
'host' => '127.0.0.1',
'username' => '',
'password' => '',
'dbname' => '',
'port' => 3306,
'charset' => 'utf8mb4',
],
'base_url' => 'http://example.com/',
];
add it to the version control
then in your application bootstrap file have a code like this:
<?php
if (!file_exists('config.php'))
{
throw new \Exception('Create config.php based on config.sample.php');
}
$config = require 'config.php';
define('BASE_URL', $config['base_url']);
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbconf = $config['db'];
$dsn = "mysql:host=$dbconf[host];dbname=$dbconf[dbname];charset=$dbconf[charset]";
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int)$e->getCode());
}
unset($dbconf, $$config['db']$config['db']);
then, as suggested, create config.php
on the every server that your application runs, each with its own set of values.