php 警告:mysqli_query() 期望参数 1 为 mysqli,在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18862743/
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
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in
提问by Philip
I am trying to build a simple custom CMS, but I'm getting an error:
我正在尝试构建一个简单的自定义 CMS,但出现错误:
Warning: mysqli_query() expects parameter 1 to be MySQLi, null given in
警告:mysqli_query() 期望参数 1 是 MySQLi,在
Why am I getting this error? All my code is already MySQLi and I am using two parameters, not one.
为什么我收到这个错误?我所有的代码都已经是 MySQLi 并且我使用了两个参数,而不是一个。
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
function getPosts() {
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}
回答by Phil
As mentioned in comments, this is a scoping issue. Specifically, $con
is not in scope within your getPosts
function.
正如评论中提到的,这是一个范围界定问题。具体来说,$con
不在您的getPosts
职能范围内。
You should pass your connection object in as a dependency, eg
您应该将连接对象作为依赖项传入,例如
function getPosts(mysqli $con) {
// etc
I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice
如果您的连接失败或发生错误,我也强烈建议停止执行。这样的东西应该就足够了
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
getPosts($con);
回答by user3169490
use global scope on your $con and put it inside your getPosts() function like so.
在您的 $con 上使用全局范围并将其放入您的 getPosts() 函数中,就像这样。
function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}
回答by staticsan
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
该getPosts()
函数似乎期望$con
是全局的,但您并没有这样声明它。
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
许多程序员将秃头全局变量视为“代码气味”。另一端的替代方案是始终传递连接资源。两者之间的中间是单例调用,它总是返回相同的资源句柄。