PHP undefined variable mysqli connection

瘦欲@ 提交于 2020-01-11 03:30:07

问题


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!


回答1:


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



回答2:


$db is a global variable to includehomepage function. If you want to access it, then you have to pass it to the function or declare it as global inside the function.

like

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

or have it as a parameter in your function and pass it via call.

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);


来源:https://stackoverflow.com/questions/25994328/php-undefined-variable-mysqli-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!