PHP PDO Database Connection Class

PHP 2 weeks ago 15,434 views Intermediate
S

sujeetkumar713

21 public snippets
15,434 Views
0 Comments
0 Saves

Description

A robust PDO connection
PHP PDO Database Connection Class.php
<?php
class Database {
    private static $instance = null;
    private $connection;

    private $host = 'localhost';
    private $dbname = 'your_database';
    private $username = 'root';
    private $password = '';

    private function __construct() {
        try {
            $this->connection = new PDO(
                "mysql:host=$this->host;dbname=$this->dbname;charset=utf8mb4",
                $this->username,
                $this->password
            );
        } catch(PDOException $e) {
            die("Connection failed: " . $e->getMessage());
        }
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance->connection;
    }
}
?>

Comments (0)

Add Comment

No comments yet. Be the first to comment!