How can global variables be used effectively in PHP to handle database connections within functions?
Global variables can be used effectively in PHP to handle database connections within functions by declaring the database connection as a global variable outside of any functions. This way, the database connection can be accessed and reused within multiple functions without having to reconnect each time. However, it is important to be cautious when using global variables to prevent potential conflicts or security vulnerabilities.
<?php
// Declare global variable for database connection
$connection = null;
function connectToDatabase() {
global $connection;
// Check if connection is already established
if ($connection === null) {
// Establish database connection
$connection = mysqli_connect("localhost", "username", "password", "database");
}
return $connection;
}
function fetchDataFromDatabase() {
global $connection;
// Connect to database if not already connected
if ($connection === null) {
connectToDatabase();
}
// Query database and fetch data
$result = mysqli_query($connection, "SELECT * FROM table");
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $data;
}
// Example usage
$data = fetchDataFromDatabase();
print_r($data);
?>