What are the potential pitfalls of using global variables in PHP for database access?

Using global variables for database access in PHP can lead to security vulnerabilities and make the code harder to maintain and debug. It is recommended to use a more structured approach such as dependency injection or a database class to encapsulate database operations.

// Using dependency injection to pass the database connection to a class method
class Database {
    private $connection;

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

    public function fetchData() {
        // Use $this->connection to access the database
    }
}

// Instantiate the database class with the database connection
$connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$database = new Database($connection);

// Call the method to fetch data
$database->fetchData();