PHP未定义变量mysqli连接 [英] PHP undefined variable mysqli connection

查看:180
本文介绍了PHP未定义变量mysqli连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a mysql connection which is included in a separate file:

require 'settings.php';

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

and I have a file with all functions, also included:

require 'functions.php';

在设置中看起来像这样:

In the settings there it looks like this:

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

和一个函数使用这种连接,如下所示:

and a function uses this connection like this:

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'];
        }

但是我收到这样的错误消息:

But I get an error message like this:

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

你有答案吗?该变量必须在包含的文件中定义.感谢您的回答!

Do you have an answer? The variable have to be defined in the included file.. I am confused. Thanks for your answers!

推荐答案

变量范围问题.查看 global

Variable scope problem. Look at 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'];
}

这篇关于PHP未定义变量mysqli连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆