PHP OOP database connect

PHP OOP database connect

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Refactoring Legacy PHP Database Patterns into Modern OOP

The code snippet provided demonstrates a classic pattern from the early days of PHP development: procedural logic wrapped inside a class shell. While it is technically functional, treating a database connection as a series of discrete function calls like db_connect(), slect_db(), and query() often leads to fragile applications that are difficult to maintain or extend. To truly leverage Object-Oriented Programming (OOP) principles, you need to shift from executing actions to managing state within the object itself.

The primary architectural issue in the provided example is the lack of encapsulation regarding connection lifecycle management. The current approach requires manual sequencing of method calls before any data retrieval can occur. This creates a rigid execution flow where the order of operations is dictated by imperative statements rather than the internal state of the class. A more robust OOP design initializes the connection within the constructor, ensuring that the database context is established immediately upon instantiation.

Consider replacing the db_connect(), slect_db(), and subsequent methods with a constructor that handles initialization:

class Database {
    protected $pdo;

    public function __construct($host = 'localhost', $dbname = 'shop') {
        // Using PDO is the modern standard, replacing deprecated mysql_* functions
        $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
        try {
            $this->pdo = new PDO($dsn, 'root', 'password');
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            throw new PDOException("Database connection failed: " . $e->getMessage());
        }
    }

    public function query($sql) {
        return $this->pdo->query($sql);
    }

    public function fetchAll() {
        return $this->query('SELECT * FROM users')->fetchAll(PDO::FETCH_ASSOC);
    }
}

This refactoring eliminates the need for manual chaining. The connection state is now an instance property ($this->pdo), and the class handles its own setup. This approach adheres to the principle of encapsulation, hiding the complexity of the underlying driver (whether it is mysql, mysqli, or PDO) behind a clean interface.

Furthermore, relying on deprecated functions like mysql_* introduces significant security risks. The original code does not use prepared statements, making it vulnerable to SQL injection attacks. In modern PHP development, using PDO or MySQLi with prepared statements is mandatory for any application handling user input. For example, instead of concatenating variables directly into the SQL string, you should bind parameters:

$statement = $this->pdo->prepare("SELECT * FROM users WHERE username = :username");
$statement->execute(['username' => $input]);

This not only secures the application but also improves performance through query caching.

Another critical trade-off to consider is resource management. The original code includes a db_close() method, which is generally unnecessary when using PDO or MySQLi in persistent connection modes common in web servers. Connections are typically pooled and reused by the server process. However, if you must close connections, ensure it happens within a context manager or try-catch block to prevent resource leaks in case of exceptions.

If you are building a larger application framework, integrating this logic into a Service Provider pattern (common in Laravel) allows for centralized configuration and dependency injection. This reduces coupling between your business logic and the database layer. For those looking to explore further patterns for decoupling services from frameworks, resources like https://laravelcompany.com offer insights into how modern ecosystems handle service registration and binding.

Ultimately, the goal of OOP in this context is not just to wrap functions in a class, but to manage state, enforce encapsulation, and provide a secure, extensible interface for data access. By moving away from procedural chains of commands to stateful objects with prepared statements, you create code that is safer, cleaner, and easier to test.

Our network