mysqli::query(): mysqli object is already closed / couldn't fetch mysqli error
The error mysqli::query(): Couldn't fetch mysqli or the modern equivalent Uncaught Error: mysqli object is already closed is a classic symptom of serialization issues in PHP, not necessarily a problem with your SQL syntax or connection logic. It occurs when an object containing a database connection is serialized (stored in a session, sent via AJAX, or pickled), deserialized into a new request context, and then used without re-establishing that specific connection.
In the code snippet provided, the root cause lies in how the EventCalendar class handles the $DBConnect object within its lifecycle methods, specifically __construct, __destruct, and __wakeup.
The Serialization Trap
When you include a file containing a global $DBConnect variable inside an object's constructor via include("inc_LadleDB.php"), you are creating a dependency on external state. If that same connection object is later serialized (for example, if the class instance is stored in $_SESSION) and then deserialized:
- Deserialization (
__wakeup): The magic method__wakeupattempts to restore the$DBConnectproperty. In your implementation, this method re-includesinc_LadleDB.php, capturing the global variable$DBConnectfrom that file scope and assigning it to the object's private property. - The Disconnect: Crucially, the original connection established in step 1 is lost. The
mysqliextension does not automatically reconnect based on credentials stored inside a serialized object; it relies on the specific socket or TCP connection handle. If the original connection was closed by the server (due to idle timeouts) or if the deserialization process breaks the link, the object now holds an invalid reference. - Execution Failure: When you subsequently call
$this->DBConnect->query(), themysqliextension checks the internal state of the handle. If it detects that the underlying connection is closed or missing (a "frozen" object), it throws the "Couldn't fetch mysqli" error.
Why __destruct Exacerbates the Issue
Your destructor logic contains a subtle logical flaw:
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
This block attempts to close the connection only if connect_error is false. While well-intentioned, this pattern assumes that a valid connection always exists. In a serialization context, if the object is deserialized but the underlying network resource has been severed, accessing $this->DBConnect immediately triggers the error you are seeing before the code even reaches your business logic. Furthermore, relying on __destruct for cleanup in web applications is risky because garbage collection timing is non-deterministic.
The Correct Pattern: Dependency Injection
To resolve this, you must decouple the database connection from the class state and manage the connection lifecycle explicitly. The standard practice in modern PHP development (including Laravel) is Dependency Injection.
Instead of creating or fetching the connection inside the class, pass it in via the constructor. This ensures the object never holds a stale reference to a closed connection.
<?php
class EventCalendar {
private $DBConnect;
public function __construct($dbConnection) {
// The connection is passed in, ensuring it is valid and current.
// If you need to validate the connection here, do so immediately.
if ($dbConnection->connect_error) {
throw new RuntimeException("Database connection failed: " . $dbConnection->connect_error);
}
$this->DBConnect = $dbConnection;
}
// Remove __destruct and __wakeup entirely. They are unnecessary
// when using Dependency Injection correctly.
public function addEvent($Date, $Title, $Description) {
if ((!empty($Date)) && (!empty($Title))) {
// Prepare statements prevent SQL injection, a critical security fix
// alongside the connection logic issue.
$stmt = $this->DBConnect->prepare("INSERT INTO tblSignUps (EventDate, Title, Description) VALUES (?, ?, ?)");
// Bind parameters safely
$stmt->bind_param("sss", $Date, $Title, $Description);
if ($stmt->execute()) {
echo "Event added successfully.";
} else {
echo "Error executing query: " . $stmt->error;
}
$stmt->close();
}
}
}
// Usage in your application bootstrap or controller
$DBConnect = new mysqli("localhost", "root@localhost", NULL, "Ladle");
// Handle connection errors immediately if needed
if ($DBConnect->connect_error) {
die("Connection failed: " . $DBConnect->connect_error);
}
$calendar = new EventCalendar($DBConnect);
$calendar->addEvent('2023-10-27', 'Zodiac Festival', 'Annual event.');
Security and Best Practices
Beyond fixing the object lifecycle, the original SQL construction in your addEvent method is vulnerable to SQL injection. You are interpolating variables directly into the query string:
$SQLString = "INSERT INTO tblSignUps (EventDate, Title, Description) VALUES('$Date', '$Title', '$Description')";
If a user inputs a malicious string into $Date, it could alter the SQL command. Always use prepared statements with parameter binding as shown in the refactored example above. This approach is not only safer but also often performs better because the database server can cache the execution plan for the query structure.
Finally, avoid using @ to suppress errors when creating a new mysqli object (as seen in $DBConnect = @new mysqli(...)). Suppressing errors hides critical failures during development and makes debugging significantly harder. Let the script halt or log the error so you can address the root cause immediately.
