Create a reusable PHP database class using PDO for secure MySQL connections with prepared statements to prevent SQL injection and optimize performance. 🔒💻
Suggestion 💡
Suggestion for better database management:
For better performance 🚀 and to avoid creating multiple database connections 🔄, consider using the Singleton Pattern. This ensures only one database connection is created and reused throughout your application. 🔑💼
Reusable PHP Database Connection Class Using PDO for Secure MySQL Queries
Database.php
<?php
// Database.php - Reusable Database Class
require_once "Config.php";
class Database {
private $pdo;
private $stmt;
public function __construct() {
try {
$dsn = "mysql:host=" . Config::get("host") . ";dbname=" . Config::get("dbname") . ";charset=utf8mb4";
$this->pdo = new PDO($dsn, Config::get("username"), Config::get("password"), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
} catch (PDOException $e) {
error_log("Database connection failed: " . $e->getMessage());
die("Database connection error.");
}
}
}
?>
Config.php
<?php
class Config {
private static array $settings = [
'host' => 'localhost',
'dbname' => 'testdb',
'username' => 'root',
'password' => ''
];
public static function get($key) {
return self::$settings[$key] ?? null;
}
}
?>
test.php
<?php
require_once 'Database.php';
try {
$db = new Database();
echo "✅ Database connection successful!";
} catch (Exception $e) {
echo "❌ Error: " . $e->getMessage();
}
?>