我正在尝试构建一个简单的自定义CMS,但出现错误:
警告:mysqli_query()期望参数1为MySQLi,在中为null
为什么会出现此错误?我所有的代码已经是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>"; } }
如评论中所述,这是一个范围界定问题。具体来说,$con不在您的getPosts功能范围内。
$con
getPosts
您应该将连接对象作为依赖项传入,例如
function getPosts(mysqli $con) { // etc
如果连接失败或发生错误,我也强烈建议停止执行。这样的东西就足够了
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions $con=mysqli_connect("localhost","xxxx","xxxx","xxxxx"); getPosts($con);