What are the implications of using global variables in PHP scripts, especially when dealing with database queries?

Using global variables in PHP scripts can lead to potential security vulnerabilities and make the code harder to maintain and debug. When dealing with database queries, using global variables can increase the risk of SQL injection attacks. It is recommended to avoid using global variables and instead pass variables as parameters to functions or use PHP's superglobals like $_POST or $_GET.

// Avoid using global variables in PHP scripts when dealing with database queries

// Example of passing variables as parameters to a function
function getUserData($userId, $conn) {
    $sql = "SELECT * FROM users WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc();
}

// Example of using PHP superglobals
$userId = $_POST['user_id'];
$conn = new mysqli("localhost", "username", "password", "database");
$userData = getUserData($userId, $conn);