Home >Backend Development >PHP Tutorial >Why Does `mysqli_query()` Return 'expects parameter 1 to be mysqli, null given'?
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
This error arises when attempting to execute a MySQL query using mysqli_query(), but the provided parameter for the connection object is not a valid MySQLi object. The mysqli_query() function expects the first parameter to be an instance of the mysqli class.
In the provided code snippet, the error is likely caused due to the following reason:
Scoping Issue
The mysqli connection object $con, which is declared in the global scope, is not accessible within the getPosts() function. This results in the null value being passed as the first parameter to mysqli_query(), leading to the error.
Solution:
To resolve this issue, you can explicitly pass the connection object to the getPosts() function as a parameter. Here's the modified code:
function getPosts(mysqli $con) { $query = mysqli_query($con, "SELECT * FROM Blog"); // ... Rest of the code remains the same }
Now, when you call the getPosts() function, be sure to pass the connection object as an argument.
Additionally, it's a good practice to enable error reporting and handle database connection issues gracefully. Here's an example:
// Enable error reporting mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Establish database connection $con = mysqli_connect("localhost", "xxxx", "xxxx", "xxxxx"); // Check connection status if (!$con) { throw new Exception('Failed to connect to MySQL: ' . mysqli_connect_error()); } // Call the getPosts() function with the connection object getPosts($con);
The above is the detailed content of Why Does `mysqli_query()` Return 'expects parameter 1 to be mysqli, null given'?. For more information, please follow other related articles on the PHP Chinese website!