What are the potential alternatives to including the config file in each function for database operations in PHP?

The issue with including the config file in each function for database operations in PHP is that it can lead to code duplication and make maintenance more difficult. A better approach is to include the config file once at the beginning of your script and then use global variables or constants to access the database connection throughout your application.

// Include the config file once at the beginning of your script
include 'config.php';

// Define global variables for database connection
global $db_host, $db_user, $db_password, $db_name;
$db_host = 'localhost';
$db_user = 'root';
$db_password = 'password';
$db_name = 'database_name';

// Function to connect to the database
function connect_to_db() {
    global $db_host, $db_user, $db_password, $db_name;
    $conn = new mysqli($db_host, $db_user, $db_password, $db_name);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    return $conn;
}

// Example function using the database connection
function get_users() {
    $conn = connect_to_db();
    $result = $conn->query("SELECT * FROM users");
    $users = $result->fetch_all(MYSQLI_ASSOC);
    $conn->close();
    return $users;
}

// Example usage
$users = get_users();
foreach ($users as $user) {
    echo $user['name'] . "<br>";
}