mysqli并访问同一个数据库中的两个不同的表

时间:2012-10-11 18:28:34

标签: php mysql mysqli

最近我得到了一个错误未定义的变量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;       
}

1 个答案:

答案 0 :(得分: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;       
}