Home > Backend Development > PHP Tutorial > Why Does `mysqli_query()` Return 'Warning: mysqli_query() expects parameter 1 to be MySQLi, null given'?

Why Does `mysqli_query()` Return 'Warning: mysqli_query() expects parameter 1 to be MySQLi, null given'?

DDD
Release: 2024-12-18 17:12:11
Original
587 people have browsed it

Why Does `mysqli_query()` Return

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
}
Copy after login

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:

  • Handle errors and connection failures by using mysqli_report() to set error reporting options.
  • Stop script execution if a connection error or a query error occurs using mysqli::error().

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template