PHP undefined variable mysqli connection
18,159
Solution 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'];
}
Solution 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);
Related videos on Youtube
Author by
fredkid
Updated on July 11, 2022Comments
-
fredkid over 1 year
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!
-
fredkid about 9 yearsthank you! now there is just one more error: Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in ..
-
ʰᵈˑ about 9 yearsAltered answer. Dont quote the 0 in "<backtick>". It'll think 0 is a column name, and kill the query.
[Err] 1054 - Unknown column '0' in 'where clause'
. Quote strings in'
, or"
. -
ʰᵈˑ about 9 yearsYou're welcome @fredkid. How this site works is to accept an answer once it's successfully answered your question, to "close" your question and to inform others what worked best for you. Both answers here are correct, please accept either one. :)
-
maxhb over 7 yearsPlease avoid using global vars. Use
function includehomepage($db) {...}
instead!