0

最近我收到一个错误 undefined variable mysqli ,我想知道 - 是不是因为我正在访问同一个数据库中的两个不同的表?

$mysqli = new mysqli('localhost', 'myuser', 'qwerty', 'mydb');

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
    //initialise vars
    $username = $_POST['username'];

    $checkRecord = $mysqli->query("SELECT information, blahblah FROM table1 WHERE username='$username' AND field1='$field1' AND field2=$field2");

    if(!$checkRecord->num_rows) 
    {
        echo "nothing retreived";
    }   
    else
    {
        $catch = $checkRecord->fetch_object();

        $newsessionnumber = get_new_session_number($username, $ip, $userAgent);

        $senddata = array(
            'newsessionnumber' => $newsessionnumber,
            'info' => $catch->information, 
            'blahblah' => $catch->blahblah, 
            'username' => $username 
        );

        echo json_encode($senddata); 
    }   
}

function get_new_session_number($username, $ip, $userAgent)
{   
    $mysqli->query("INSERT INTO sessionnumberdispatch VALUES (NULL, '$username', NOW(), '$ip', '$userAgent')");

    $newsessionnumber = $mysqli->insert_id;
    return $newsessionnumber;       
}
4

1 回答 1

2

$mysqli对象在内部没有得到识别get_new_session_number()

使用global关键字:

function get_new_session_number($username, $ip, $userAgent)
{   
    global $mysqli;
    $mysqli->query("INSERT INTO sessionnumberdispatch VALUES (NULL, '$username', NOW(), '$ip', '$userAgent')");

    $newsessionnumber = $mysqli->insert_id;
    return $newsessionnumber;       
}
于 2012-10-11T18:34:22.203 回答