Warning: Understanding mysqli_query() Parameter Error
When using mysqli_query() in PHP, it's crucial to ensure that the first parameter is a valid mysqli object representing a database connection. However, if you encounter an error stating "Warning: mysqli_query() expects parameter 1 to be mysqli, null given in," it indicates that the first parameter passed to the function is not a mysqli object.
Examining the Code
In your provided code, you have a function called getPosts(). This function attempts to query a database table named Blog. However, in the mysqli_query() call within getPosts(), the first parameter is not explicitly passed. As a result, PHP assumes the value of $con, which is declared outside the function, as the first parameter. But, $con is not in the scope of getPosts() and hence returns null.
Resolving the Error
To resolve this issue, you have two options:
Example:
function getPosts(mysqli $con) { // ... same code as before } // Connect to the database $con = mysqli_connect("localhost", "xxxx", "xxxx", "xxxxx"); // Call getPosts() with the connection as a parameter getPosts($con);
Additional Recommendations
It's also advisable to handle any potential errors that may occur during database operations. You can enable error reporting explicitly as follows:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
This will throw exceptions if any errors occur, allowing you to take appropriate action in your code.
The above is the detailed content of Why does `mysqli_query()` return a 'Warning: mysqli_query() expects parameter 1 to be mysqli, null given' error?. For more information, please follow other related articles on the PHP Chinese website!