PHP database connection class

PHP database connection class

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

Stefan Bogdanescu

Founder & Senior Architect

PHP Database Connection Class Patterns and Modern Migration Paths

The snippet you provided touches on a fundamental concept in object-oriented programming: encapsulation. In your example, you want to retrieve a user ID from a database within a class. The core issue isn't just writing the function; it's about how that function interacts with the database resource itself. In modern PHP development, relying directly on mysql_fetch_array inside a method without establishing a context or handling resources properly is a significant pitfall.

The code snippet you shared uses the deprecated mysql_* extension, which was removed in PHP 5.5 and is no longer supported in current versions of PHP. Attempting to run that specific code today will result in fatal errors. Furthermore, storing raw database connections or results as static properties (often implied when connecting inside a class method) leads to state pollution across requests. A robust database connection class must handle the lifecycle of the connection explicitly.

To properly retrieve a user ID, you need to separate the concern of "connecting" from "querying." Here is a more structured approach using PDO, which is the standard for modern PHP applications:

class DatabaseConnection {
    private $pdo;

    public function __construct($dsn, $username, $password) {
        // Establish connection only once per instance
        try {
            $this->pdo = new PDO($dsn, $username, $password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]);
        } catch (PDOException $e) {
            // Handle connection errors appropriately
            throw new RuntimeException("Database connection failed: " . $e->getMessage());
        }
    }

    public function getUserById($id) {
        $sql = "SELECT uid FROM users WHERE id = :id LIMIT 1";
        $stmt = $this->pdo->prepare($sql);
        
        $result = $stmt->execute([':id' => $id]);
        
        if ($result && $row = $stmt->fetch()) {
            return $row['uid'];
        }

        return null; // Or throw an exception if the user is missing
    }
}

This implementation demonstrates several critical patterns. First, the constructor initializes the connection, ensuring that every instance has its own valid context. Second, it uses prepared statements with placeholders (:id) instead of concatenating strings. This prevents SQL injection vulnerabilities, which are common when retrieving dynamic data like user IDs. Finally, it returns a specific value or null to indicate failure, allowing the caller to handle the logic gracefully.

One of the most common mistakes beginners make is assuming that a single static connection serves all classes globally. While a singleton pattern can manage a global database instance, injecting dependencies (like passing the database object into your class constructor) is generally preferred for testability and clarity. If you are building a larger application, managing these connections manually becomes error-prone.

This is where frameworks like Laravel shine. Laravel provides an elegant facades system and dependency injection containers that abstract away much of this boilerplate code. Instead of writing the connection logic from scratch, you can define your models in app/Models/User.php and access the database through Eloquent ORM:

use App\Models\User;

class UserService {
    public function getUid(int $id): ?int {
        return User::find($id)?->uid;
    }
}

This approach leverages Laravel's built-in connection pooling and query optimization. It handles the underlying PDO logic, error reporting, and migration schemas automatically. If you are starting a new project and want to avoid reinventing the wheel for database interactions, exploring resources like https://laravelcompany.com can provide further insights into how modern PHP frameworks simplify data persistence.

In summary, moving from procedural database calls to encapsulated classes requires shifting from "how do I connect?" to "how do I manage the connection lifecycle and secure the queries." By using prepared statements, avoiding deprecated extensions, and leveraging established frameworks when appropriate, you ensure your application remains secure, maintainable, and compatible with current PHP standards.

Our network