Warning: mysqli_query() expects parameter 1 to be mysqli, null given in PHP [duplicate]
I'm having trouble with using a mysqli_query
inside a function, error: Warning: mysqli_query() expects parameter 1 to be mysqli, null given
. If I var_dump($dbc)
outside of the function I get the expected result but when I use it inside the function I get NULL
returned.
Here is my connection script:
define('DB_HOST', 'localhost');
define('DB_DBNAME', 'db');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DBNAME)or die(mysqli_error($dbc));
Here is my function:
function memInfo($var1, $var2){
var_dump($dbc);
$query = mysqli_query($dbc, "SELECT * FROM `members` WHERE id = '".$var1."'")or die(mysqli_error($dbc));
$rowCount = mysqli_num_rows($query);
if($rowCount > 0){
$fetch = mysqli_fetch_array($query);
return $fetch[$var2];
}else{
return "Invalid member";
}
}
Variables declared inside functions have function scope. You need to prefix them with global to access global variables.
function memInfo() {
global $dbc;
}
Alternatively, you can pass-in the variable as a parameter of the function.
Your $dbc variable inside function memInfo is considered as "function scope" variable. If you need to use the global instance (previously defined $dbc = mysqli_ blah blah...) you need to declare as "global scope" inside your function. Like this:
function memInfo($var1, $var2){
global $dbc;
var_dump($dbc);
$query = mysqli_query($dbc, "SELECT * FROM `members` WHERE id = '".$var1."'")or die(mysqli_error($dbc));
$rowCount = mysqli_num_rows($query);
if($rowCount > 0){
$fetch = mysqli_fetch_array($query);
return $fetch[$var2];
}else{
return "Invalid member";
}
}
More on this subject in php manual:
http://php.net/language.variables.scope.php
精彩评论