Home > Backend Development > PHP Tutorial > Why Does My MySQLi Code Throw 'mysqli::query(): Couldn't fetch mysqli' Errors?

Why Does My MySQLi Code Throw 'mysqli::query(): Couldn't fetch mysqli' Errors?

Mary-Kate Olsen
Release: 2024-12-04 10:17:14
Original
186 people have browsed it

Why Does My MySQLi Code Throw

MySQLI Error: Object Is Closed or Fetching Error

Issue Description

The error message "mysqli::query(): Couldn't fetch mysqli in line 43" signifies a connection problem with the MySQL database.

Code Snippet

The code segment mentioned includes a connection file ("inc_LadleDB.php") and a class ("EventCalendar") that interacts with the database. Here's the relevant code:

// Connection file
$DBConnect = @new mysqli("localhost", "root@localhost", NULL, "Ladle");

// Class constructor
function __construct() {
    include("inc_LadleDB.php");
    $this->DBConnect = $DBConnect;  
}

// Class destructor
function __destruct() {
    if (!$this->DBConnect->connect_error) {
        $this->DBConnect->close();
    }
}
Copy after login

Cause

The error arises due to the database connection being closed prematurely, specifically in the destructor method "__destruct()". When the object is destroyed, it closes the database connection, but subsequent queries continue to attempt to execute, leading to the error.

Solution(s)

To resolve the issue, ensure that the database connection remains open during the execution of all queries. One possible solution is to remove the "close()" statement from the destructor. Consider the following modification:

// Class destructor
function __destruct() {
    // Do not close the connection here
}
Copy after login

Tip

Remember, the "__destruct()" method is automatically called when an object is destroyed, so closing the connection there may lead to errors if other queries or database operations are still being performed.

The above is the detailed content of Why Does My MySQLi Code Throw 'mysqli::query(): Couldn't fetch mysqli' Errors?. 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