PHP未定义变量mysqli连接

时间:2014-09-23 11:48:15

标签: php mysql variables undefined

我有一个mysql连接,它包含在一个单独的文件中:

require 'settings.php';

我有一个包含所有功能的文件,还包括:

require 'functions.php';

在设置中,它看起来像这样:

$db = mysqli_connect("host", "username", "passwort", "database");
    if(!$db) {
        exit("Error: ".mysqli_connect_error());
    }

并且函数使用这样的连接:

function includehomepage() {
            $data = array();
            $query = "SELECT pagecontent FROM `pages` WHERE `id` = `0`";
            $query = mysqli_query($db, $query);
            $data = mysqli_fetch_assoc($query);
            return $data['pagecontent'];
        }

但是我收到如下错误消息:

Undefined variable: db in /var/... on line 18

你有答案吗?变量必须在包含的文件中定义..我很困惑。谢谢你的回答!

2 个答案:

答案 0 :(得分:4)

可变范围问题。看global

function includehomepage() {
   global $db;
   $data = array();
   $query = "SELECT pagecontent FROM `pages` WHERE `id` = '0'";
   $query = mysqli_query($db, $query);
   $data = mysqli_fetch_assoc($query);
   return $data['pagecontent'];
}

答案 1 :(得分:2)

$ db是includehomepage函数的全局变量。如果要访问它,则必须将其传递给函数或在函数内将其声明为全局。

function includehomepage() {
     global $db;   
     $data = array();
     $query = "SELECT pagecontent FROM `pages` WHERE `id` = '0'";
     $query = mysqli_query($db, $query);
     $data = mysqli_fetch_assoc($query);
     return $data['pagecontent'];
}

或将其作为函数中的参数并通过调用传递。

function includehomepage($db) {
     $data = array();
     $query = "SELECT pagecontent FROM `pages` WHERE `id` = '0'";
     $query = mysqli_query($db, $query);
     $data = mysqli_fetch_assoc($query);
     return $data['pagecontent'];
}
includehomepage($db);