問題描述
我正在嘗試構建一個簡單的自定義 CMS,但出現錯誤:
I am trying to build a simple custom CMS, but I'm getting an error:
警告:mysqli_query() 期望參數 1 是 MySQLi,在
Warning: mysqli_query() expects parameter 1 to be MySQLi, null given in
為什么我會收到這個錯誤?我所有的代碼都已經是 MySQLi 并且我使用了兩個參數,而不是一個.
Why am I getting this error? All my code is already MySQLi and I am using two parameters, not one.
$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>";
}
}
推薦答案
正如評論中提到的,這是一個范圍界定問題.具體來說,$con
不在您的 getPosts
函數范圍內.
As mentioned in comments, this is a scoping issue. Specifically, $con
is not in scope within your getPosts
function.
您應該將連接對象作為依賴項傳入,例如
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);
這篇關于警告:mysqli_query() 期望參數 1 是 mysqli,在的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!