Understanding "Warning: mysqli_query() expects parameter 1 to be MySQLi, null given in" Error
In your attempt to create a custom CMS, you encountered the following error message:
"Warning: mysqli_query() expects parameter 1 to be MySQLi, null given in"
Cause of the Error
This error indicates that the mysqli_query() function, which executes SQL queries, expects a MySQLi object as its first parameter. However, in your getPosts() function, you are passing a null value instead of a MySQLi object.
Solution
The solution to this issue is to ensure that the $con MySQLi object is within the scope of the getPosts() function. In your code, $con is defined in the global scope, but it is not accessible within the function.
Passing the MySQLi Object as a Dependency
One way to address this is to pass the MySQLi object to the getPosts() function as a dependency. Here's how you can do it:
function getPosts(mysqli $con) { // etc }
By making the MySQLi object a parameter of the function, you ensure that it is available within the function's scope and can be used by mysqli_query().
Additional Recommendations
In addition to resolving the scoping issue, consider implementing the following recommendations:
Here's an example of how to implement these recommendations:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions $con=mysqli_connect("localhost","xxxx","xxxx","xxxxx"); if (!$con) { throw new Exception("Failed to connect to MySQL: " . mysqli_connect_error()); } getPosts($con);
By implementing these recommendations, you can ensure the robustness and reliability of your custom CMS.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3