将mysqli连接传递给PHP函数 - 不同步

I have a problem when performing mysql commands when I invoke a function in another file. If I have the code in the same file, it works fine. The code looks like:

authenticate:

{
    $conn = new mysqli($dbserver, "dbuser", "pass", $dbname);
    $sql = 'SELECT userId, salt, pwd, isAdmin FROM users where username = ?';
    $stmt = $conn->stmt_init();
    $stmt->prepare($sql);
    $stmt->bind_param('s', $username);
    $stmt->bind_result($userId, $salt, $storedPwd, $isAdmin);
    $stmt->execute();
    $stmt->fetch();
}

Now, if I call a function, immediately after fetch, it fails on the bind_param line. I call it like this:

updateUserActivity ($conn, $tpcLang, 'LI', $userId);

the beginning of this function is:

function updateUserActivity ($conn, $lang, $activityType, $userId)
{
    // check that activity is valid
    $sql = 'SELECT activityType
            FROM activityType  
            WHERE activityType = ?';
    $stmt = $conn->stmt_init();
    $stmt->prepare($sql);
    $stmt->bind_param('s', $activityType);
    $stmt->bind_result($activityTypeInDB);
    $stmt->execute();
    $stmt->fetch();

    if ($activityType == $activityTypeInDB){
        $success=1;
    } else {
       $success=0;
       $msg = $lang->get('UPDATE_USER_INVALID_ACTIVITY_ERROR_MSG') . " " . $activityType . " (" . $stmt->errno . "):  " . $stmt->error;
       error_log ($msg);
    }
    // continue on to add a row in the userActivity table
} 

The error I get on the bind_param is: invalid object or resource mysqli_stmt, and the DB error is: Commands out of sync; you can't run this command now.

Any suggestions would be greatly appreciated.

try adding this after your fetch.

mysqli_free_result($result);

or

mysqli_close($conn);