How can the use of global variables be avoided when working with MySQL in PHP?

Using global variables can lead to potential security risks and make the code harder to maintain. To avoid using global variables when working with MySQL in PHP, you can encapsulate your database connection and query functions within a class. This way, you can create an instance of the class whenever you need to interact with the database, without relying on global variables.

class Database {
    private $host = 'localhost';
    private $username = 'username';
    private $password = 'password';
    private $database = 'dbname';
    private $conn;

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

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

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

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