What best practices should be followed when handling database queries and results in PHP functions?

When handling database queries and results in PHP functions, it is important to properly sanitize input data to prevent SQL injection attacks. Additionally, always use prepared statements to securely execute queries and avoid direct concatenation of user input into SQL queries.

// Example of a function that handles a database query using prepared statements

function getUserInfo($userId, $conn) {
    $stmt = $conn->prepare("SELECT username, email FROM users WHERE id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return $row;
    } else {
        return false;
    }
}