简体   繁体   English

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

[英]mysqli and accessing two different tables in same db

lately I've been getting an error undefined variable mysqli and I was wondering - is it because I'm accessing two different tables in the same database? 最近我得到一个错误未定义的变量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;       
}

The $mysqli object is not getting recognized inside get_new_session_number() . $mysqli对象未在get_new_session_number()被识别。

Use the global keyword: 使用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;       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM