In what scenarios would it be advisable to use a database class to manage and track MySQL queries in PHP?

Using a database class to manage and track MySQL queries in PHP is advisable in scenarios where you have a complex database structure, multiple queries to execute, and the need for error handling and logging. By encapsulating database operations within a class, you can easily reuse code, ensure consistency, and improve maintainability.

class Database {
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'my_database';
    private $connection;

    public function __construct() {
        $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

    public function query($sql) {
        $result = $this->connection->query($sql);
        if (!$result) {
            echo "Error executing query: " . $this->connection->error;
        }
        return $result;
    }

    public function close() {
        $this->connection->close();
    }
}

// Example usage
$db = new Database();
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
    echo "Name: " . $row['name'] . "<br>";
}
$db->close();