Database Connection Class

PHP

Author: ahambridge

10 months ago 1,667 B


<?php

require_once __DIR__ . '/vendor/autoload.php';

use Dotenv\Dotenv;

class Database
{
    private $host;
    private $dbName;
    private $username;
    private $password;

    public function __construct()
    {
        $dotenv = Dotenv::createImmutable(__DIR__);
        $dotenv->load();

        $this->host = $_ENV['DB_HOST'];
        $this->dbName = $_ENV['DB_DATABASE'];
        $this->username = $_ENV['DB_USERNAME'];
        $this->password = $_ENV['DB_PASSWORD'];

        $this->connect();
    }

    private function connect()
    {
        try {
            $dsn = "mysql:host=$this->host;dbname=$this->dbName;charset=utf8mb4";
            $this->connection = new PDO($dsn, $this->username, $this->password);
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo "Database successfully established";
        } catch (PDOException $e) {
            die("Database connection failed: " . $e->getMessage());
        }
    }

    public function getConnection()
    {
        return $this->connection;
    }
}
?/ >


// For this to work must have a .env file with text, should be stored like this
DB_HOST=plesk.remote.ac
DB_DATABASE=##
DB_USERNAME=##
DB_PASSWORD=##


// There is another file you need to install, to run the install, the code is..
<?php
exec('php composer.phar require vlucas/phpdotenv', $output, $return_var);
echo implode("\n", $output);
?>


// Then to implement this into a project, and require the connection. The code is..
    require_once 'database.php';
    $db = new Database();
    $conn = $db->getConnection();