Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
What is the best way to close a mysql connection?
  • Using the show full processlist; command when connected to our app's mysql db, I can see processes that are in the SLEEP state. 

    It is not clear what is causing this, but I would like to try explicitly closing the db connection to see if that clears these processes.

    My question is, where is the best place to do this? I was thinking in the after() method of the controller. Is there a better place?

    I am also confused as to the best way to go about this. I see that the __destruct() method will close the connection, but I don't know exactly how to call that.

    // Destroy the database instance
    unset(static::instances[(string) $db], $db);

    The config value for this db instance is 'mysql'.

    Thank you for your insight on this.


  • You don't need to do that, every Connection object has an __destruct() that will explicitly do a disconnect. If you don't trigger it with an unset(), PHP will trigger it when the request is finished.

    If connections aren't closed, have you configured your application to use persistent connections (which will not be closed by the above mechanism)?

    You can control the time the process waits for a new connection through the "wait_timeout" config setting in your my.cnf.

  • Thank you for your help with this. The app is running on Pagoda and the sleep processes do appear in between page requests, but sometimes it takes 4 seconds for a request to go through as a simple UPDATE query waits.

    The sleep processes go away once the page is loaded, but there is an occasional one that will remain indefinitely.

    So there is no need to close the connection manually?

  • No, unless there is a PHP bug on the version Pagoda uses that prevents the __destruct() magic method from being called. But I've never seen one.

    If you insist you want to do it yourself, create a shutdown event that closes it. This should be enough:

    DB::instance()->disconnect();
  • Thank you for your help. They moved me to a new node and the DB is super quick now.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion