Home >Backend Development >PHP Tutorial >Why Does `mysqli_query()` Return 'Warning: mysqli_query() expects parameter 1 to be MySQLi, null given'?
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.
The above is the detailed content of Why Does `mysqli_query()` Return 'Warning: mysqli_query() expects parameter 1 to be MySQLi, null given'?. For more information, please follow other related articles on the PHP Chinese website!