How can the problem of having an empty $query variable in the calling page be resolved when using a function to handle MySQL queries?

The issue of having an empty $query variable in the calling page when using a function to handle MySQL queries can be resolved by ensuring that the $query variable is passed as a parameter to the function. This way, the function will have access to the query string and can execute it properly.

// Function to handle MySQL queries
function executeQuery($query) {
    // Connect to the database
    $conn = mysqli_connect("localhost", "username", "password", "database");

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    // Execute the query
    $result = mysqli_query($conn, $query);

    // Close the connection
    mysqli_close($conn);

    return $result;
}

// Call the function with the query string
$query = "SELECT * FROM table_name";
$result = executeQuery($query);

// Process the result
while ($row = mysqli_fetch_assoc($result)) {
    // Do something with the data
}