48

Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43

The following is my connection file:

<?php
if(!isset($_SESSION)) 
{ 
    session_start(); 
}  

// Create array to hold error messages (if any)
$ErrorMsgs = array();

// Create new mysql connection object
$DBConnect = @new mysqli("localhost","root@localhost", 
            NULL,"Ladle");

// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {

    // Add error to errors array
    $ErrorMsgs[]="The database server is not available.".
               " Connect Error is ".$DBConnect->connect_errno." ".
               $DBConnect->connect_error.".";
}
?>

This is my class:

 <?php 
    class EventCalendar {
        private $DBConnect = NULL;
        
        function __construct() {
            // Include the database connection data
            include("inc_LadleDB.php");
            $this->DBConnect = $DBConnect;  
        }
        
        function __destruct() {
            if (!$this->DBConnect->connect_error) {
                $this->DBConnect->close();
            }
        }
        
        function __wakeup() {
            // Include the database connection data
            include("inc_LadleDB.php");     
            $this->DBConnect = $DBConnect;
        }
        
        
        // Function to add events to Zodiac calendar
        public function addEvent($Date, $Title, $Description) {
            // Check to see if the required fields of Date and Title have been entered
            if ((!empty($Date)) && (!empty($Title))) {
                /* if all fields are complete then they are 
                   inserted into the Zodiac event_calendar table */
                $SQLString = "INSERT INTO tblSignUps".
                           " (EventDate, Title, Description) ".
                           " VALUES('$Date', '$Title', '".
                            $Description."')";
            
                // Store query results in a variable
                $QueryResult = $this->DBConnect->query($SQLString);

I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the @new mysqli parameters. Can anyone help me to understand what is going wrong?

When executing the same on PHP 8, I can observe a similar error that states:

Uncaught Error: mysqli object is already closed

Dharman
  • 30,962
  • 25
  • 85
  • 135
codingManiac
  • 1,654
  • 4
  • 29
  • 42

4 Answers4

112

Probably somewhere you have DBconnection->close(); and then some queries try to execute .


Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 1
    had the same problem "mysqli::query(): Couldn't fetch mysqli". googled it and found this answer. i was closing it too late. After connecting and quering the DB i included a new php-file which didnt know the connection so it message was shown. just commenting if anyone else runs in this problem. cheers – Ferdinand Fatal Apr 11 '16 at 14:04
  • Kudos, T.T. Lesson learned: don't allow anything to destroy the DB object via a __destruct() method. – Kevin_Kinsey Aug 31 '18 at 19:32
  • @T.Touda __destruct is not no fired after CLASS construction but "The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. " See: https://www.php.net/manual/en/language.oop5.decon.php – Alex Mar 18 '20 at 07:48
  • try getting new mysqli instance before running the query – Jorge Wander Santana Ureña Oct 06 '22 at 15:43
6

Reason of the error is wrong initialization of the mysqli object. True construction would be like this:

$DBConnect = new mysqli("localhost","root","","Ladle");
Aycan Yaşıt
  • 2,106
  • 4
  • 34
  • 40
  • 2
    Can you explain why exactly the original code is "wrong"? If the credentials were wrong (and that is the only change I see), there should be a clear error message about that – Nico Haase Feb 27 '19 at 08:55
  • @NicoHaase It's simple, password for root user is empty string, and `NULL` is provided. When credentials are incorrect, error message is generally like given error at top of the question. – Aycan Yaşıt Feb 27 '19 at 11:52
  • 2
    @AycanYaşıt but in which case would you get the error message "Couldn't fetch mysqli" when providing wrong credentials? Additionally, the documentation states that when using no argument, a user without a password is selected – Nico Haase Feb 27 '19 at 12:17
5

I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.

$db_connection = new mysqli("127.0.0.1","root","","db_name");
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ratnadeep
  • 1,125
  • 1
  • 15
  • 30
-6

Check if db name do not have "_" or "-" that helps in my case

Gorodeckij Dimitrij
  • 4,209
  • 2
  • 17
  • 21
  • Can you explain further how that connects? There should be another very clear error message if something would be wrong with the database name, and both types of dashes are allowed to be used in a database name – Nico Haase Feb 27 '19 at 08:57
  • I can't explain that, but find that by experimental, seems any dash broke command interpreter and don't work. If DB name doesn't have dashes - it is perfect. Spend on that 6 hours then first time meet. People who downvote that don't understand and never meet that so they don't know that is working, even if its look silly. – Gorodeckij Dimitrij Jan 23 '20 at 16:23
  • Well, I still don't understand. Under which circumstances does that make a difference? In the given PHP code, there is no such "command interpreter" – Nico Haase Jan 23 '20 at 16:25
  • PHP it is interpreter :) have such with WordPress recently. Yes, PHP itself doesn't have restriction how you name it, but exact error code you will get if rename DB with a dash – Gorodeckij Dimitrij Jan 23 '20 at 16:28
  • And you've received the error message "Couldn't fetch mysqli" when using a database name with a dash? Or are you talking about a different error message? – Nico Haase Jan 23 '20 at 16:30
  • exactly this error: mysqli::query(): Couldn't fetch mysqli will have new WordPress install this weekend - will check how about that with the newest version – Gorodeckij Dimitrij Jan 23 '20 at 16:32