Home >Backend Development >PHP Tutorial >Why Does `mysqli_query()` Throw 'expects parameter 1 to be mysqli, null given'?

Why Does `mysqli_query()` Throw 'expects parameter 1 to be mysqli, null given'?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 07:01:10197browse

Why Does `mysqli_query()` Throw

Understanding "mysqli_query() expects parameter 1 to be mysqli, null given in"

When encountering this error, it indicates a mismatch between the expected data type and the provided value in a MySQLi function. In this specific instance, the query function is not receiving a valid MySQLi object as its first parameter.

In the provided code, you've defined a connection object $con using MySQLi. However, the getPosts() function, where the error occurs, does not have access to this connection object within its scope. Therefore, when attempting to query the database, it passes null instead of the expected mysqli object as the first parameter.

To resolve this issue, you need to make $con accessible within the getPosts() function by passing it as an argument. This allows the function to use the connection object to execute queries properly.

Additionally, it's recommended to catch MySQLi errors and handle them appropriately, such as by halting execution or displaying an error message. This ensures that the application responds to database issues gracefully.

The above is the detailed content of Why Does `mysqli_query()` Throw 'expects parameter 1 to be mysqli, null given'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn