php 警告:mysqli_query() 期望参数 1 为 mysqli,给定为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18933107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:31:10  来源:igfitidea点击:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given

phpfunctionmysqli

提问by scleveland04

I'm sure this is a duplicate, but I can not find an answer to this. For whatever reason, I can not query my database.

我确定这是重复的,但我找不到答案。无论出于何种原因,我都无法查询我的数据库。

Simply I am trying to call a function but I get the error...

只是我试图调用一个函数,但我收到错误...

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ... on line 12

My dbConnect.php file has

我的 dbConnect.php 文件有

$adConn = mysqli_connect("myHost","myUser","myPword","myDB");

My functions.php files has

我的functions.php文件有

require "dbConnect.php";

// Check connection
if (mysqli_connect_errno($adConn))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

//-------------------------------------------------//
//   Gets total number of games for a given week   //
//-------------------------------------------------//
function GetGamesCount($wID){
    $sql = "SELECT * FROM schedule WHERE weekID=$wID";

    $gamesRS = mysqli_query($adConn, $sql);
    $games = mysqli_fetch_array($gamesRS);


}

I get no error from the connection check, I have tried putting it within the funcation as well. I know I can use the mysqli_num_rows function, which I will. I just need to figure out why it won't query the database. I have tried querying with other functions with the same problem. However, if I query within the page or using ajax from a separate file, I have no problems.

我没有从连接检查中得到任何错误,我也尝试将它放在函数中。我知道我可以使用 mysqli_num_rows 函数,我会的。我只需要弄清楚为什么它不会查询数据库。我曾尝试使用具有相同问题的其他函数进行查询。但是,如果我在页面内查询或使用单独文件中的 ajax,则没有问题。

I just don't see what I'm missing. Any help is greatly appreciated.

我只是不明白我错过了什么。任何帮助是极大的赞赏。

回答by John Conde

Because $adConnis declared outside of the function is not in scope. That means you do not have access to it inside the function. To have access to it you need to pass it as aparameter of the function.

因为$adConn在函数之外声明的不在作用域内。这意味着您无法在函数内部访问它。要访问它,您需要将它作为函数的参数传递。

 function GetGamesCount($wID, $adConn){

回答by sangi93

$adConnis in the global scope and you cannot access it from the function, if you change $adConnto $GLOBALS['adConn']it should work.

$adConn是在全球范围内,你不能从功能访问它,如果你改变$adConn$GLOBALS['adConn']它应该工作。