What are the best practices for structuring PHP code to avoid confusion and errors when working with multiple database tables?

When working with multiple database tables in PHP, it's important to follow best practices to avoid confusion and errors. One way to structure your code is to use object-oriented programming principles, such as creating separate classes for each database table and using methods to interact with the database. This helps to keep your code organized and makes it easier to maintain and troubleshoot.

class User {
    private $db;

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

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

class Product {
    private $db;

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

    public function getProductById($id) {
        $query = "SELECT * FROM products WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->execute(['id' => $id]);
        return $stmt->fetch();
    }
}

// Usage
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$user = new User($db);
$product = new Product($db);

$userData = $user->getUserById(1);
$productData = $product->getProductById(1);