Connect to a MySQL database using PDO

Using PDO to connect to your MySQL database effectively:

// Connect to the Database server
$driver = 'mysql';
$host = '';
$port = 3306;
$socket = ''; // Optional
$username = '';
$password = '';
$database = '';
$options = [
	\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_OBJ,
	\PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
	\PDO::ATTR_EMULATE_PREPARES   => true,
	\PDO::ATTR_CURSOR             => \PDO::CURSOR_FWDONLY,
];
try {
	// Get the Connexion's DSN
	if (empty($socket)) {
		$dsn = $driver . ':host=' . $host . ';port=' . $port . ';dbname=' . $database . ';charset=utf8';
	} else {
		$dsn = $driver . ':unix_socket=' . $socket . ';dbname=' . $database . ';charset=utf8';
	}
	// Connect to the Database Server
	$pdo = new \PDO($dsn, $username, $password, $options);
	
} catch (\PDOException $e) {
	die("Can't connect to the database server. ERROR: " . $e->getMessage());
} catch (\Exception $e) {
	die("The database connection failed. ERROR: " . $e->getMessage());
}

You can check out all PDO constant here: http://php.net/manual/en/pdo.constants.php