Home >Backend Development >PHP Tutorial >Why Does My `mysqli_query()` Function Receive a Null Value Instead of a MySQLi Connection Object?
Understanding "Warning: mysqli_query() expects parameter 1 to be mysqli, null given in"
In your quest to create a custom CMS, you may have encountered the dreaded error message: "Warning: mysqli_query() expects parameter 1 to be MySQLi, null given in." This frustrating problem often arises from a misunderstanding regarding the scope of variables within PHP functions.
Cause of the Error
The error suggests that your getPosts() function is attempting to access the $con variable, which stores your MySQLi connection object, but it's not accessible within that function's scope. This is because $con is defined outside of the getPosts() function.
Solution: Passing the Connection as Dependency
To resolve this issue, you need to pass the connection object to the getPosts() function as a dependency. By doing this, the function can access the connection and perform the necessary database operations.
function getPosts(mysqli $con) { // Code to query the database using $con }
Preventing Further Errors
To minimize potential issues, consider using the following code to handle connection errors and throw exceptions:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions $con = mysqli_connect("localhost", "xxxx", "xxxx", "xxxxx"); getPosts($con);
Additional Tips
The above is the detailed content of Why Does My `mysqli_query()` Function Receive a Null Value Instead of a MySQLi Connection Object?. For more information, please follow other related articles on the PHP Chinese website!