仅在一个页面上找不到数据库连接变量

时间:2015-09-23 10:44:04

标签: php mysqli

连接文件是:

$DBconnect = mysqli_connect("localhost", "root", "", "project" );

这适用于除了一个之外的所有页面,这会产生此错误: 未定义的变量:DBconnect

这部分:

include_once('connection.php');
// Function that will convert a user id into their username
function getusername($uid) {

$res = mysqli_query($DBconnect, "SELECT username FROM users WHERE id='".$uid."' LIMIT 1") or die(mysql_error());

感谢您的建议

2 个答案:

答案 0 :(得分:0)

更改此

    function getusername($uid){
$res = mysqli_query($DBconnect, "SELECT username FROM users WHERE id='".$uid."' LIMIT 1") or die(mysql_error());
}

到这个

    function getusername($uid){
    global $DBconnect;
    $res = mysqli_query($DBconnect, "SELECT username FROM users WHERE id='".$uid."' LIMIT 1") or die(mysql_error());
    }

function getusername($uid,$DBconnect){
        $res = mysqli_query($DBconnect, "SELECT username FROM users WHERE id='".$uid."' LIMIT 1") or die(mysql_error());
        }

答案 1 :(得分:0)

这是一个范围问题。

$DBConnect在全局范围内可用,但您无法自动访问函数中的全局范围。所以将$DBConnect作为参数传递给函数,一切都很好。

include_once('connection.php');

function getusername($uid, $DBConnect) {

    $res = mysqli_query($DBconnect, "SELECT username 
                                     FROM users 
                                     WHERE id='$uid' LIMIT 1"); 
    if ( ! $res ) {
       echo mysql_error();
       exit;
    }

}

// call function with an extra parameter i.e. the $DBConnect

getusername($uid, $DBConnect);