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

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

Linda Hamilton
Release: 2024-12-15 00:58:17
Original
339 people have browsed it

Why Does `mysqli_query()` Return

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template