Skip to content
PHP Logo

Are there any potential pitfalls in using a PHP class as an abstraction of a database table?

One potential pitfall in using a PHP class as an abstraction of a database table is the risk of exposing sensitive database operations or structure details to the outside world. To solve this issue, it's important to properly encapsulate the class properties and methods to only allow safe and controlled access to the database.

php
class User {
    private $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    public function getUserById($id) {
        $query = $this->db->prepare("SELECT * FROM users WHERE id = :id");
        $query->bindParam(':id', $id);
        $query->execute();
        return $query->fetch();
    }

    // Add more methods for safe database operations here
}