Pdoexception sqlstate hy000 general error 2006 mysql server has gone away

I'm doing an operation that inserts hundreds of records into a MySQL database. After inserting exactly 176 records I get this error: [PDOException] SQLSTATE[HY000]: General error: 2006 MySQL serve...

I would venture to say the problem is with wait_timeout. It is set to 30 seconds on my shared host and on my localhost is set for 28800.

I found that I can change it for the session, so you can issue the query: SET session wait_timeout=28800

UPDATE The OP determined that he also needed to change the variable interactive_timeout as well. This may or may not be needed for everyone.

The code below shows the setting before and after the change to verify that it has been changed.

So, set wait_timeout=28800 (and interactive_timeout = 28800) at the beginning of your query and see if it completes.

Remember to insert your own db credentials in place of DB_SERVER, DB_USER, DB_PASS, DB_NAME

UPDATE Also, if this does work, you want to be clear on what you are doing by setting wait_timeout higher. Setting it to 28800 is 8 hours and is a lot.

The following is from this site. It recommends setting wait_timeout to 300 — which I will try and report back with my results (after a few weeks).

wait_timeout variable represents the amount of time that MySQL will
wait before killing an idle connection. The default wait_timeout
variable is 28800 seconds, which is 8 hours. That’s a lot.

I’ve read in different forums/blogs that putting wait_timeout too low
(e.g. 30, 60, 90) can result in MySQL has gone away error messages. So
you’ll have to decide for your configuration.

<?php

$db = new db();

$results = $db->query("SHOW VARIABLES LIKE '%timeout%'", TRUE);
echo "<pre>";
var_dump($results);
echo "</pre>";

$results = $db->query("SET session wait_timeout=28800", FALSE);
// UPDATE - this is also needed
$results = $db->query("SET session interactive_timeout=28800", FALSE);

$results = $db->query("SHOW VARIABLES LIKE '%timeout%'", TRUE);
echo "<pre>";
var_dump($results);
echo "</pre>";


class db {

    public $mysqli;

    public function __construct() {
        $this->mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
        if (mysqli_connect_errno()) {
            exit();
        }
    }

    public function __destruct() {
        $this->disconnect();
        unset($this->mysqli);
    }

    public function disconnect() {
        $this->mysqli->close();
    }

    function query($q, $resultset) {

        /* create a prepared statement */
        if (!($stmt = $this->mysqli->prepare($q))) {
            echo("Sql Error: " . $q . ' Sql error #: ' . $this->mysqli->errno . ' - ' . $this->mysqli->error);
            return false;
        }

        /* execute query */
        $stmt->execute();

        if ($stmt->errno) {
            echo("Sql Error: " . $q . ' Sql error #: ' . $stmt->errno . ' - ' . $stmt->error);
            return false;
        }
        if ($resultset) {
            $result = $stmt->get_result();
            for ($set = array(); $row = $result->fetch_assoc();) {
            $set[] = $row;
            }
            $stmt->close();
            return $set;
        }
    }
}

Update: Save yourself the time of reading this entire thread and set max_allowed_packet as documented.

Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 204 of C:rndproprietaryrnd.emr.phdrupal-7.x-devincludessession.inc).

os: ubuntu

Comments

keichee’s picture

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT b.* FROM {block} b WHERE (b.theme = :db_condition_placeholder_0) AND (b.status = :db_condition_placeholder_1) ORDER BY b.region ASC, b.weight ASC, b.module ASC; Array ( [:db_condition_placeholder_0] => bartik [:db_condition_placeholder_1] => 1 ) in _block_load_blocks() (line 708 of C:rndproprietaryrnd.emr.phdrupal-7.x-devmodulesblockblock.module).

os: ubuntu and windows

  • Log in or register to post comments

keichee’s picture

Logo Here
Error

The website encountered an unexpected error. Please try again later.
Error messagePDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {cache_update} cache_update WHERE ( (cid = :db_condition_placeholder_0) ) FOR UPDATE; Array ( [:db_condition_placeholder_0] => update_project_data ) in _update_cache_set() (line 763 of C:rndproprietaryrnd.emr.phdrupal-7.x-devmodulesupdateupdate.module).
Uncaught exception thrown in shutdown function.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 11447990474d22d35a7f86c2.09295213 ) in lock_release_all() (line 247 of C:rndproprietaryrnd.emr.phdrupal-7.x-devincludeslock.inc).

Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 204 of C:rndproprietaryrnd.emr.phdrupal-7.x-devincludessession.inc).

  • Log in or register to post comments

keichee’s picture

Logo Here
Error

The website encountered an unexpected error. Please try again later.
Error messagePDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {cache_update} cache_update WHERE ( (cid = :db_condition_placeholder_0) ) FOR UPDATE; Array ( [:db_condition_placeholder_0] => update_project_data ) in _update_cache_set() (line 763 of C:rndproprietaryrnd.emr.phdrupal-7.x-devmodulesupdateupdate.module).
Uncaught exception thrown in shutdown function.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 18847400194d22d440b23367.75208826 ) in lock_release_all() (line 247 of C:rndproprietaryrnd.emr.phdrupal-7.x-devincludeslock.inc).

Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 204 of C:rndproprietaryrnd.emr.phdrupal-7.x-devincludessession.inc).

  • Log in or register to post comments

univate’s picture

Category: bug » support
Priority: Critical » Normal
  • Log in or register to post comments

keichee’s picture

nope, i can go to the ?q=user and other parts but not the admin

  • Log in or register to post comments

keichee’s picture

Logo Here
Error

The website encountered an unexpected error. Please try again later.
Error messagePDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT b.* FROM {block} b WHERE (b.theme = :db_condition_placeholder_0) AND (b.status = :db_condition_placeholder_1) ORDER BY b.region ASC, b.weight ASC, b.module ASC; Array ( [:db_condition_placeholder_0] => bartik [:db_condition_placeholder_1] => 1 ) in _block_load_blocks() (line 708 of C:rndproprietaryrnd.emr.phdrupal-7.x-devmodulesblockblock.module).
Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: UPDATE {users} SET access=:db_update_placeholder_0 WHERE (uid = :db_condition_placeholder_0) ; Array ( [:db_update_placeholder_0] => 1294130151 [:db_condition_placeholder_0] => 1 ) in _drupal_session_write() (line 214 of C:rndproprietaryrnd.emr.phdrupal-7.x-devincludessession.inc).

  • Log in or register to post comments

Damien Tournoud’s picture

It means that your MySQL server is configured with a ridiculously small timeout. See the page of the MySQL manual linked in #4 for solutions.

  • Log in or register to post comments

keichee’s picture

Category: support » bug
Priority: Normal » Critical

drupal must auto connect to mysql server if that timeout happen, i guess drupal wont autoconnect on the fly

  • Log in or register to post comments

tim.plunkett’s picture

Comment #9

tim.plunkett

Primary language English

Location Philadelphia

CreditAttribution: tim.plunkett commented 5 January 2011 at 06:35

Category: bug » support
Priority: Critical » Normal
  • Log in or register to post comments

Crell’s picture

Status: Active » Postponed (maintainer needs more info)

Drupal doesn’t connect to MySQL until the first query is sent. A request almost never takes more than a second, and usually less than half a second. If your MySQL server is timing out in that amount of time it means MySQL is misconfigured.

Please verify that you have a reasonable wait_timeout. I suspect simply increasing that will solve the problem.

  • Log in or register to post comments

wouter99999’s picture

I got similar errors with a new installation on 64bit Windows 7. This has to do with maximum allowed packet size in MySQL. To solve, add in the [mysqld] section in my.ini: max_allowed_packet=100M and restart MySQL

  • Log in or register to post comments

madhavvyas’s picture

  • Log in or register to post comments

keichee’s picture

Status: Postponed (maintainer needs more info) » Closed (fixed)
  • Log in or register to post comments

keichee’s picture

  • Log in or register to post comments

joe casey’s picture

#12 above worked for me.

WAMP on Windows 7 localhost. Site ran fine but devel module dpm() call blew up with the ‘MySQL server has gone away’ message.

#12 solved it, #13 didn’t help in my case.

  • Log in or register to post comments

Julia_yl’s picture

#12 above worked for me too thanks lots

  • Log in or register to post comments

wildermuthn’s picture

  • Log in or register to post comments

muschpusch’s picture

maybe not related but the solution from #20 worked for me. I got sleeping mysql processes running forever (until max connections where reached). It was when visiting admin/config in D7.8

  • Log in or register to post comments

BassPlaya’s picture

I’ve done the same thing as wouter99999 instructed in #12 (in a my.cnf file, copied from my-medium.cnf file) does but I extended it to 256M. I’m running MAMP Free and I must say that one site still gives me the error message when I’m trying to add a content type and the other doesn’t. No idea why the other doesn’t. If anyone knows, please share.

  • Log in or register to post comments

BassPlaya’s picture

it really is the 256M that does the trick. If I set it to 100M it throws that nasty error.

  • Log in or register to post comments

majingas’s picture

#12 worked for me aswell. Wamp on wun 7 64.

  • Log in or register to post comments

phprf’s picture

#12 Worked great for me! Wamp on Win7 Pro 64bit. Many thanks and God bless!

  • Log in or register to post comments

wwgrey’s picture

WAMP on Windows 7 localhost:
#12 removed the issue
Thanks !

  • Log in or register to post comments

shasha_s’s picture

hello,

on Acquia dev desktop, win7 I changed in my.cfn

max_allowed_packet=128M to 256M

but I still get this, when I want to add new content type.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
and
Uncaught exception thrown in session handler.

PDOException: There is already an active transaction in _drupal_session_write() (line 206 of…

how can I solve it?

thank you.
S.

  • Log in or register to post comments

kappaluppa’s picture

  • Log in or register to post comments

Tamanda’s picture

I had a similar problem, turned out the comment (#12) by wouter99999 fixed it. Thanks wouter99999, you saved me from a world of pain!!

  • Log in or register to post comments

clashar’s picture

wouter99999, thank you! your solution from #12 helped me well.

  • Log in or register to post comments

latulipeblanche’s picture

  • Log in or register to post comments

garypigott39’s picture

#12 fixed my issue, but it had to be in the [mysqld] section (edited via WAMP «my.ini» option)
Cheers for the post.

  • Log in or register to post comments

krisrobinson’s picture

Just highlighting this (#34) , make sure it’s in the [mysqld] section, by default there is the same setting in the [mysqldump] section, can be confusing for some.

  • Log in or register to post comments

ahenfo’s picture

Version: 7.x-dev » 7.14
Priority: Normal » Major
Status: Closed (fixed) » Active

I have tried all the solutions given above but I’m still getting the same error message(MESSAGE BELOW). I am running Zend Server CE with the my-huge.ini as the default my.ini. I need help because all my drupal projects are inaccessible.

Error
The website encountered an unexpected error. Please try again later.
Error messagePDOException: SQLSTATE[42000]: Syntax error or access violation: 1286 Unknown table engine ‘InnoDB’: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in lock_may_be_available() (line 167 of C:ZendApache2htdocsacademy.orgincludeslock.inc).

Uncaught exception thrown in shutdown function.
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1286 Unknown table engine ‘InnoDB’: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 68667015250329455dbcd27.47278376 ) in lock_release_all() (line 269 of C:ZendApache2htdocsacademy.orgincludeslock.inc).

  • Log in or register to post comments

rogical’s picture

max_allowed_packet = 16M solved my problem

  • Log in or register to post comments

Exlord’s picture

max_allowed_packet=100M fixed mine … tanks …

  • Log in or register to post comments

cluther’s picture

Comment #41

cluther

Primary language English

Location Austin, Texas

CreditAttribution: cluther commented 29 September 2012 at 22:16

NOTE: I found this to be a very time consuming and frustrating problem to solve. I leave this post as search bait to help others with a similar issue.

On my Drupal 7 site I was experiencing WSOD when attempting to add/edit a menu item (/structure/menu/item//edit), content type (admin/structure/types/manage/) or feature (admin/structure/features/create). All the tips provided at http://drupal.org/node/158043 on dealing with WSOD were of no help. I increased my PHP memory and added error reporting statements to index.php (see http://drupal.org/node/158043), but still there was the White Screen of Death and a total lack of insightful messages in any of the error log files (watchdog, php, apache, sql).

Further experimenting, I tried simplifying my environment. After I turned off DEVEL and I was presented with a Fatal error: Exception thrown without a stack frame in Unknown on line 0 error when visiting the page. Not a fix, but much better than a blank screen.

I then found a tip at http://www.drupal4hu.com/node/222 which suggested the issue might be one of the following:

  1. There was an exception while handling an exception.
  2. There was an exception while running a destructor.
  3. There was an exception while closing the session.
  4. There was an exception while running a shutdown function.

I followed the writer’s recommendation of wrapping my index.php within a try-catch block and saving the catch to an error log. My index.php file now looks like:

try{
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 * ...
 */

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

} catch (exception $e) {file_put_contents('/tmp/drupal_error.log', $e->getMessage() . ' file: ' . $e->getFile() . ' on line '. $e->getLine()); }

NOTE: Less the ending ?>.

I visited the page again and noticed that the following error was written to my drupal_error.log file.
SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

Which then led me to this page and to posts 12 & 13. If you follow post 13’s link you will find the following:

This is very critical error found in MySQL. This error originate when you are dealt with huge records. There are various unanswered forum you will found when you Google that problem. The reason behind this crash is packet size. By default, MySQL configuration max_allowed_packet is set it to 16M. This settings may introduce this exception in your website..

Solution:
To resolve that problem you needs to increase max_allowed_packet variable in MySQL. Add following line in my.ini (or my.cnf)
max_allowed_packet=100M

Save the file and restart MySQL service. Now onward you will never get that kind exception in your open source / website.

I’m using MAMP on MacOS. So I modified the MySQL’s my.cnf file and upped the max_allowed_packet default from 1M to 100M. Saved and rebooted MAMP. Problem solved. Yeah!

  • Log in or register to post comments

Raffy Martinez’s picture

Updated to 7.16 and got the error. # 12 worked but instead of 100M i set it at max_allowed_packet = 10M.

Thanks.

  • Log in or register to post comments

ydahi’s picture

Comment #43

ydahi

Location Waterloo, Canada

CreditAttribution: ydahi commented 2 November 2012 at 01:55

After moving my site to a vps I started seeing this error. The error was volatile and I could not reproduce manually — it was very sporadic.

I attempted to fix it by increasing the max_packet_size, however this didn’t work.

I noticed some references to the theme registry in the error. My site utilizes Zen.

I went into the appearance admin section and turned off «Rebuild theme registry on every page. » in the theme settings.

This fixed the solution for me.

  • Log in or register to post comments

mrudolph’s picture

As with ydahi (#43), it was the Zen theme which caused the aforementioned error with SQL, this after I had updated to Zen 7.x-5.1. No more playing with Zen, I guess!

  • Log in or register to post comments

willisiw’s picture

Posted by wouter99999 on February 26, 2011 at 6:44pm
I got similar errors with a new installation on 64bit Windows 7. This has to do with maximum allowed packet size in MySQL. To solve, add in the [mysqld] section in my.ini: max_allowed_packet=100M and restart MySQL

Perfect! Fixed my error on WAMP. I thought it had to do with my install of Commerce as it happened right behind installing a Commerce Module.

  • Log in or register to post comments

shankarpmenon’s picture

#12 is not working for me,
i am using wamp my sql 5.5

i have two web site working locally. one is working fine but the other is not working when i click add content type or edit a content type. but other wise the site is working perfectly.

  • Log in or register to post comments

ticocr’s picture

it seemed that drupal needed more packages when reading from databases since limit was set to 1M for some reason it was the default since there was not config file.

the site was still working, since for normal use it doesn’t take that much from the database, but when logged into the administration panel it did take a lot data from mysql, over 1M as it was set….. It was working with all the modules that I already installed but not all configured and up and running, since some of them were in the off mode… I just Enabled some features of some modules on the modules panel and started giving me that error, nothing displayed other than showing that error where said: «SERVER HAS GONE AWAY»…

my first reaction was::: FUCK!! as usual.. then i started thinking.. and my first though was to remove some modules from the modules folder, but then I figured that some modules are needed by other modules.. so that would take forever, … then I realized that it was showing a server issue… so i thought it was apache.. then mysql, and i started looking for mysql config file and no file found.,.. then I started reading about it mysql website and it popped up

so i knew it was mysql-server configuration, then I saw a post in drupal that said it was the packages drupal was getting from mysql… so what need to be modify was:

max_allowed_packet=1M to 2 or more Megs in mysql’s my.cnf file.

  • Log in or register to post comments

bisonbleu’s picture

Ran into the same problem. This post on StackOverflow fixed it for me.

Skip-locking was removed in MySQL 5.5. See here. Edit your my.cnf file and change «skip-locking» to «skip-external-locking».

My setup:
— MAMP 1.9.6.1 (PHP 5.3.5, mySQL 5.5.9)
— MAMP/conf/my.cnf
— Drupal 7.21

  • Log in or register to post comments

albertosouza’s picture

I’m using gnu/linux fedora and add the setting of max_allowed_packet like comment #12 in the file /etc/my.cnf did not work.
After some testing i could change the configuration max_allowed_packet using the /etc/my.cnf.d/server.cnf and now the error gone away from my pc

  • Log in or register to post comments

afoster’s picture

#12 worked for MAMP 2.1.1. on OSX 10.8

  • Log in or register to post comments

namjoo’s picture

hi
sorry for my english
i test it and solve my problem.
in mysql shell insert this command
mysql >> SET GLOBAL max_allowed_packet=32*1024*1024;
and then import database

my os is centos 5

  • Log in or register to post comments

famishedroad’s picture

#12 worked perfectly for me! Many thanks.

  • Log in or register to post comments

NineAllexis’s picture

#12 worked for me, too! Thanks alot!

  • Log in or register to post comments

maikelm’s picture

Thanks, that’s the general solution

  • Log in or register to post comments

cwpates’s picture

Component: mysql database » ajax system

For what It’s worth, last step in installing Drupal Commons, this worked for me. Thanks..

  • Log in or register to post comments

alifspb’s picture

Default Re: High load: mysql —log-error=/var/lib/mysql/…

Since you are using MySQL 5.0, please try the following values to replace your existing /etc/my.cnf file (which might not be accurate to use as MySQL had been restarted in less than 24 hours when mysqltuner.pl was run):

Code:

[mysqld]
innodb_buffer_pool_size=20M
key_buffer_size = 512M
max_allowed_packet=100M
max_connections=500
max_heap_table_size=24M
open_files_limit=5000
query_cache_size=8M
table_cache = 2200
thread_cache_size=4
tmp_table_size=40M
log-slow-queries=/var/lib/mysql/slow.log

After this, then create the slow query log using these commands:

Code:

cd /var/lib/mysql
touch slow.log
chmod 660 slow.log
chown mysql:mysql slow.log

After doing that, then restart MySQL:

Code:

/etc/init.d/mysql restart
this help me solve my problem thanks

  • Log in or register to post comments

sonekun’s picture

I was having a problem with this uncaught exception error and server has gone away message when I tried to edit an order in drupal commerce (on shared hosting). I went back to my local host and checked if it gave the same error. It gave a different error relating to drupal firebug module. I then turned off Drupal Firebug and Drupal for Firebug Preprocessor modules. The error went away. Hope this helps somebody.

  • Log in or register to post comments

lprancourt’s picture

#12 Seems to solve this issue, but my website is hosted and I don’t have access to that specific file. It is really bugging me as I can’t use my admin user at all, I’m stuck. Everything was working well and have been for the last 3 months, on a production server, than I had many spams and tried to put in antispam module, and boom, now my admin user gets the WSOD , but not restricted users.

The site is still available for most, but my admin is dead, I really need to fix this, but I don’t know how to change that setting in a shared server environment.

Thank for any help you can provide!

  • Log in or register to post comments

MariskaTh’s picture

I’m having a similar problem while trying to install Drupal 7.

After installing 27 modules (of 28) I get the following message:

‘An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: http://localhost/drupal/install.php?profile=standard&locale=en&id=1&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => menu_rebuild ) in lock_may_be_available() (line 167 of C:wampwwwdrupalincludeslock.inc).Uncaught exception thrown in shutdown function.PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 802228002541876118e8773.14607894 ) in lock_release_all() (line 269 of C:wampwwwdrupalincludeslock.inc).Uncaught exception thrown in session handler.PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] => ZLNqcOjZv5_OY8Y_fNwE0Il6hHmlJCLVL9qK5XUBTIo [:db_condition_placeholder_1] => ) in _drupal_session_write() (line 209 of C:wampwwwdrupalincludessession.inc).’

I have raised the number of the max_allowed_packet to various high amounts.
I have installed WAMP anew.
I have raised other numbers in my my.ini.
Each time I delete Drupal, my databank and my history in Chrome.

I have tried a lot of things, but I do not manage to install Drupal correctly. What can I try next?

Thanks,
Mariska.

  • Log in or register to post comments

ximix’s picture

#12 worked for me, too!! Thanks alot!!

  • Log in or register to post comments

Tharick’s picture

  • Log in or register to post comments

schellenbergk’s picture

#12 did not work for me — and I’m still flailing about trying to install Drupal (been at this since March 17). If anyone can help I will really appreciate it. It seems Mariska #61 is having similar issues…

Here’s what I’ve tried.

• Installed wampserver 64-bit on my Windows 7 64-bit machine following the instructions on the drupalize.me video

• Installed Drupal 7.35 per the instructions on the drupalize.me video but at Step 26 I get a “General error: 2006 MySQL server has gone away” error. WAMP goes from green to orange immediately at this step.

• Uninstalled wampserver 64-bit, reinstalled and (per #12) changed the MySQL “my.ini” file line “max_allowed_packet” from 1M to 100M. Reinstalled Drupal, but at Step 26 I get the same error.

• Uninstalled wampserver 64-bit, reinstalled and (per #12) changed the MySQL “my.ini” file line “max_allowed_packet” from 1M to 100M. Also (per another page at Drupal.org) changed [wampmysql] to [wampmysql64]. Reinstalled Drupal 7.35, but at Step 26 I get the same error.

• Uninstalled wampserver 64-bit, installed wampserver 32-bit and (per #12) changed the MySQL “my.ini” file line “max_allowed_packet” from 1M to 100M. Reinstalled Drupal 7.35, but at Step 26 I get the same error.

It’s obviously something wrong with MySQL – but what? I’ve search all over the internet, and the MaxPackets solution in #12 seems to fix it for most people but not for me?

Please can anyone help?

  • Log in or register to post comments

AlexFMartin’s picture

I was trying to install 7.36 locally and kept getting the a similar issue as Mariska #61 and schellenbergk #66. I configured my mysql settings to consume more resources and have a longer timeout and it did nothing! I couldn’t figure out why it was still throwing the ajax error Mariska was getting. When I checked the mysql log file it kept saying that I didn’t have permissions. I’m on win7 so…yes…I do have permission. Why had I been able to do this on my old computer all the time, and not this one? The only difference I could find was that McAfee came installed on this one (I had been using avast). When I disabled it I was able to install drupal on my localhost like normal! Very frustrating, so if that’s the situation you find yourself in, give it a try. It might save you some time, if you can remember to turn your antivirus back on one you’re installed :)

  • Log in or register to post comments

schellenbergk’s picture

So after simply waiting a few weeks, I tried again and the issue has gone away. It seems the latest version has fixed whatever incompatibilities existed in the Windows configuration that I and a handful of other had.

Many thanks!!

  • Log in or register to post comments

MichaelJOC2’s picture

I had this error and came up with my own fix.

I am using wampp on windows 7. The problem appeared on local host.
I tried changing the max allowed packet. No effect. I tried restarting mysql server from xampp. No effect.

Another symptom I had was that when I had the problem, on starting mysql server at first there was a message which seemed to say there was a port conflict, then mysql server said that it started successfully.

I checked for port conflicts between mysql server and some other running process but didn’t find one.

Here is what worked for me.

I used netstat to get the PID of the running mysql process (or at least whatever process was using the same port as mysql).
I then went to task manager found that process and killed it.
In xampp I restarted mysql server.

Problem fixed. I don’t really know why it worked. Best guess is that mysql had somehow started twice, or at least when it stopped it still kept some resources and/or did not stop and clear down completely.
Hope this might help someone.

  • Log in or register to post comments

mamourou’s picture

Hello , I load my drupal website via Fillezilla and it has received . When finished, in my browser I grabbed www.monsite.com/install.php to finalize the publication and once the party of choice for database I are mistakes once I selects the base all data by inserting the name of the database and password . What should I do please ?

  • Log in or register to post comments

kenorb’s picture

I had to increase to:

max_allowed_packet = 200M

Since my code was dumping very big Guzzle objects via watchdog.

  • Log in or register to post comments

janspeer’s picture

it has something todo with enabling multiple new modules in one go
and then there can be a fail

if on a shared server that works perfect for all other drupal sites with the same workload and max allowed settings and you are on a shared server
what can you do ,

  • Log in or register to post comments

Huelfe’s picture

I’ve tried everything and I didn’t get work, but then I took a look into the mysql_error.log:

[ERROR] InnoDB: The total blob data length (1066257) is greater than 10% of the total redo log size (10485760). Please increase total redo log size.

So I increased innodb_log_file_size from 5M to 256M in my.ini.

My changes in my.ini are

innodb_log_file_size = 256M

And under [mysqld] in my.ini:

max_allowed_packet = 100M

Now everything is working fine.

  • Log in or register to post comments

cilefen’s picture

  • Log in or register to post comments

MarcelMüller1978’s picture

  • Log in or register to post comments

kavbiswa’s picture

#12 worked for me too. Many thanks.

  • Log in or register to post comments

cilefen’s picture

Title: General error: 2006 MySQL server has gone away in _drupal_session_write() » General error: 2006 MySQL server has gone away in _drupal_session_write() when max_allowed_packet is not set high enough
Status: Closed (fixed) » Closed (works as designed)

I am setting the correct status because of #74.

  • Log in or register to post comments

idris_9791’s picture

#12 is not working for me.. I was changed the max execution limit but still occuring the same error. Below i have place the error details.

PDOException: SQLSTATE[HY000] [2006] MySQL server has gone away in lock_may_be_available() (line 167 of C:xamppnewhtdocscsbsrcincludeslock.inc).

Can anyone please suggest this?????

Thanks,

Idris

  • Log in or register to post comments

kenorb’s picture

  • Log in or register to post comments

jaiiali’s picture

#12 worked for me too. Many thanks.

  • Log in or register to post comments

usama009’s picture

  • Log in or register to post comments

hiramanpatil’s picture

I have updated max_allowed_packet = 200M but still not working for me.

I am using Drupal 8 on Ubuntu 14.04.

Getting below error message randomly.

The website encountered an unexpected error. Please try again later.
PDOException: SQLSTATE[HY000] [2002] Connection refused in DrupalComponentDependencyInjectionPhpArrayContainer->createService() (line 79 of /var/www/html/MYPROJECT/code/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php).

Sometimes it shows below error message as well.

The website encountered an unexpected error. Please try again later.
DrupalCoreDatabaseDatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: CREATE TABLE {cache_config} ( `cid` VARCHAR(255) BINARY CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.', `data` LONGBLOB NULL DEFAULT NULL COMMENT 'A collection of data to cache.', `expire` INT NOT NULL DEFAULT 0 COMMENT 'A Unix timestamp indicating when the cache entry should expire, or -1 for never.', `created` DECIMAL(14, 3) NOT NULL DEFAULT 0 COMMENT 'A timestamp with millisecond precision indicating when the cache entry was created.', `serialized` SMALLINT NOT NULL DEFAULT 0 COMMENT 'A flag to indicate whether content is serialized (1) or not (0).', `tags` LONGTEXT NULL DEFAULT NULL COMMENT 'Space-separated list of cache tags for this entry.', `checksum` VARCHAR(255) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL COMMENT 'The tag invalidation checksum when this entry was saved.', PRIMARY KEY (`cid`), INDEX `expire` (`expire`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT 'Storage for the cache API.'; Array ( ) in DrupalCoreConfigCachedStorage->readMultiple() (line 105 of core/lib/Drupal/Core/Config/CachedStorage.php). 

Anybody has faced this issue with Drupal 8? Please help.

Thanks

  • Log in or register to post comments

tomhung’s picture

  • Log in or register to post comments

rajeev_drupal’s picture

Increasing the max_allowed_packed to 16 M worked for me.

  • Log in or register to post comments

LAguilar’s picture

  • Log in or register to post comments

muranod’s picture

Well, that was several wasted days for a simple fix (#12 worked — had switched to XAMPP). Moral is, read ALL of the logs. THANK YOU!!

  • Log in or register to post comments

cilefen’s picture

  • Log in or register to post comments

hardik jayeshbhai hihoriya’s picture

#12 Worked for me.
Thank you very much.

  • Log in or register to post comments

madhavvyas’s picture

  • Log in or register to post comments

mariami.ta’s picture

max_allowed_packet = 100M only Worked for me on drupal 8.3.6

  • Log in or register to post comments

wolffereast’s picture

  • Log in or register to post comments

pillona’s picture

Comment #94

pillona CreditAttribution: pillona as a volunteer commented 28 September 2018 at 20:21

I spent a long time finding a solution for this, so here’s my two cents.

I had the same problem when updating an old drupal 6 website to drupal 7.
In my case I could not set max_allowed_packet to more than 32M, and with 32M I still had the error.
But actually I took a look at the session database and noticed that the table was more than 200M in a 300M database.
It seems like if all users sessions ever were still stored on the database without cleaning.
Actually, you can empty this table safely (it only has the side effect of disconnecting all active users, which in my case, as I am migrating the website to a new version, I do not care about…)

After fixing this, I could load the update.php, but ran into a similar problem this time mentioning the searchindex table, which again I cleared…

  • Log in or register to post comments

benjamin_dk’s picture

I have run into this issue as well, but raising the max_allowed_packet value to even 1024 does not help.

I don’t know what caused the error to get triggered all of a sudden. I restarted the server recently after some standard apt upgrades. There are several other sites running with a similar setup, and the problem does not happen there.

I tried several things…

  • raising the max_allowed_packet in /etc/mysql/my.cnf to 1024M
  • raising the wait_timeout in /etc/mysql/my.cnf to 600
  • raising the open_files_limit using this method
  • truncating the sessions table
  • truncating the watchdog table

Hope someone has an idea how to troubleshoot from here!

Additional uncaught exception thrown while handling exception.
Original

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT * FROM {menu_router} WHERE path IN (:ancestors_0) ORDER BY fit DESC LIMIT 0, 1; Array ( [:ancestors_0] =&gt; node ) in menu_get_item() (line 475 of /home/<user>/public_html/includes/menu.inc).
Additional

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = 'default'; Array ( [:language] =&gt; da [:source] =&gt; The website encountered an unexpected error. Please try again later. [:context] =&gt; ) in locale() (line 719 of /home/<user>/public_html/modules/locale/locale.module).
Uncaught exception thrown in session handler.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] =&gt;<somelongstring> [:db_condition_placeholder_1] =&gt;<somelongstring> ) in _drupal_session_write() (line 209 of /home/<user>/public_html/includes/session.inc). 

Specs

Ubuntu 16.04, PHP 7.1.26-1
mysql Ver 14.14 Distrib 5.7.25, for Linux (x86_64)

I have used the Drupal-VM for setting up the server, with a NGINX and Node.js service running on a VPS with 8G RAM.

$ free -m
              total        used        free      shared  buff/cache   available
Mem:           7793        1190        5541         100        1061        6228
Swap:          2047           0        2047

Configuration

my.cnf

[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock

[mysqld]
port = 3306
bind-address = 0.0.0.0
datadir = /var/lib/mysql
socket = /var/run/mysqld/mysqld.sock
pid-file = /var/run/mysqld/mysqld.pid

# Logging configuration.
log-error = /var/log/mysql/mysql.err

# Slow query log configuration.
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 2


# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links = 0

# User is ignored when systemd is used (fedora >= 15).
user = mysql

# http://dev.mysql.com/doc/refman/5.5/en/performance-schema.html
;performance_schema

# Memory settings.
key_buffer_size = 256M
max_allowed_packet = 1024M
table_open_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_type = 0
query_cache_size = 16M
query_cache_limit = 1M
max_connections = 151
tmp_table_size = 16M
max_heap_table_size = 16M
group_concat_max_len = 1024
join_buffer_size = 262144

wait_timeout = 600
lower_case_table_names = 0
event_scheduler = OFF

# This will not be respected here so we set this in /etc/systemd/system/mysql.service
# open_files_limit = 10000

# InnoDB settings.
innodb_large_prefix = 1
innodb_file_format = barracuda
innodb_file_per_table = 1
innodb_buffer_pool_size = 256M
innodb_log_file_size = 64M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 64M

[mysqld_safe]
pid-file = /var/run/mysqld/mysqld.pid

Variables:

mysql> SHOW VARIABLES LIKE 'max_allowed_packet';
+--------------------+------------+
| Variable_name      | Value      |
+--------------------+------------+
| max_allowed_packet | 1073741824 |
+--------------------+------------+
1 row in set (0.01 sec)

mysql> SHOW VARIABLES LIKE 'open_files_limit';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| open_files_limit | 10000 |
+------------------+-------+
1 row in set (0.00 sec)



mysql> SHOW VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 28800 |
+---------------+-------+
1 row in set (0.01 sec)

mysql> SELECT table_schema "mydb",
    ->         ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" 
    -> FROM information_schema.tables 
    -> GROUP BY table_schema; 
+--------------------+---------------+
| mydb                 | DB Size in MB |
+--------------------+---------------+
| mydb                 |          11.2 |
| information_schema |           0.2 |
+--------------------+---------------+
2 rows in set (0.04 sec)

Update:

I never managed to fix this error by manipulating MySQL or OS settings. After consulting with others our diagnosis pointed to corrupted tables in the database.

We could not even run simple mysql count statements against certain tables without crashing the mysql process and in the mysql.err log we had ugly errors like these:

InnoDB: Assertion failure in thread 140192398046976 in file btr0cur.cc line 7218
InnoDB: Failing assertion: space_id == page_get_space_id(page)

Luckily the tables didn’t contain vital data, so I ended up truncating the tables.

I experienced this error across different servers around the same time which makes me suspect that a hardware / storage issue might be in play.

  • Log in or register to post comments

kenorb’s picture

  • Log in or register to post comments

serialmother’s picture

#12 works — Drupal 8 php 7.2.14
Thanks

  • Log in or register to post comments

kate_raquel’s picture

  • Log in or register to post comments

atsakoumis’s picture

Version: 7.15 » 10.0.x-dev

I faced this problem in Drupal 7.72 when i try to open the new content type admin page. I changed the value of the variable «Maximum packet size» in the mySQL Server settings from 1MB to 2MB and it worked! Server System: CentOS Linux.

  • Log in or register to post comments

islamrobi’s picture

#12 worked for me, thank you so much dear.

  • Log in or register to post comments

cristian100’s picture

Comment #103

cristian100

Primary language Spanish

Location Tepic Nayarit

CreditAttribution: cristian100 as a volunteer commented 7 June 2021 at 16:12

#12 did the trick, thanks.

  • Log in or register to post comments

balwant20’s picture

I am also getting the same error. #12 resolved my error.

  • Log in or register to post comments

thalles’s picture

If you use lando:
.lando.yml

database:
    type: mysql:5.7
    portforward: true
    configuration:
      properties:
        max_allowed_packet: 77
  • Log in or register to post comments

Asked
10 years, 8 months ago

Viewed
19k times

Recently I started getting an error every time I try and add a content no matter what type. This is the error that shows up in the browser:

Additional uncaught exception thrown while handling exception.

Original
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT COUNT(cid) FROM {comment} WHERE status = :status; Array ( [:status] => 0 ) in comment_count_unpublished() (line 313 of /Applications/MAMP/htdocs/modules/comment/comment.module).

Additional

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => php [:db_insert_placeholder_2] => %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] => a:6:{s:5:»%type»;s:12:»PDOException»;s:8:»!message»;s:154:»SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT COUNT(cid) FROM {comment} WHERE status = :status; Array ( [:status] =&gt; 0 ) «;s:9:»%function»;s:27:»comment_count_unpublished()»;s:5:»%file»;s:56:»/Applications/MAMP/htdocs/modules/comment/comment.module»;s:5:»%line»;i:313;s:14:»severity_level»;i:3;} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://localhost:8888/?q=node%2Fadd%2Farcade-project&amp; [:db_insert_placeholder_7] => http://localhost:8888/ [:db_insert_placeholder_8] => 127.0.0.1 [:db_insert_placeholder_9] => 1338336955 ) in dblog_watchdog() (line 154 of /Applications/MAMP/htdocs/modules/dblog/dblog.module).

I also get the following error in my php error file:

PHP Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY000]: General error: 2006 MySQL server has gone away’ in /Applications/MAMP/htdocs/includes/database/database.inc:2136

Stack trace:
0 /Applications/MAMP/htdocs/includes/database/database.inc(2136): PDOStatement->execute(Array)
1 /Applications/MAMP/htdocs/includes/database/database.inc(664): DatabaseStatementBase->execute(Array, Array)
2 /Applications/MAMP/htdocs/includes/database/database.inc(2315): DatabaseConnection->query(‘SELECT expire, …’, Array, Array)
3 /Applications/MAMP/htdocs/includes/lock.inc(167): db_query(‘SELECT expire, …’, Array)
4 /Applications/MAMP/htdocs/includes/lock.inc(146): lock_may_be_available(‘theme_registry:…’)
5 /Applications/MAMP/htdocs/includes/theme.inc(447): lock_acquire(‘theme_registry:…’)
6 /Applications/MAMP/htdocs/includes/bootstrap.inc(427): ThemeRegistry->set(Array)
7 [internal function]: DrupalCacheArray->__destruct()
8 {main}
thrown in /Applications/MAMP/htdocs/includes/database/database.inc on line 2136

I am having a little trouble deciphering these error messages. Could anyone help me understand what’s going on here?

apaderno's user avatar

apaderno

95.5k15 gold badges158 silver badges283 bronze badges

asked May 30, 2012 at 0:34

Mike2012's user avatar

9 times out of 10 this error is caused by an insufficiently large max_allowed_packet setting in your MySQL server’s my.cnf file.

The standard default for MAMP in my experience is 1M, which isn’t usually enough for Drupal (especially considering the size of some of the cache strings it generates).

Try increasing that setting gradually to see if the error disappears. I’m sure a quick google search will tell you how to do that in MAMP.

answered May 30, 2012 at 1:01

Clive's user avatar

CliveClive

165k17 gold badges296 silver badges329 bronze badges

4

This MySQL/MariaDB error:

Error: 2006 (CR_SERVER_GONE_ERROR) — MySQL server has gone away

means basically that the client couldn’t send a question to the server.

This could happen either by temporary glitch, too big or invalid SQL query, misconfiguration of your server or limitation of your hosting provider.

In general this error could be result of several things, such as:

  • a query to the server is incorrect or too large,

    Solution: Increase max_allowed_packet variable.

    Note: Make sure the variable is under [mysqld] section, not [mysql].

    Note: Don’t forget to restart the MySQL/MariaDB server.

  • You got a timeout from the TCP/IP connection on the client side.

    Solution: Increase wait_timeout variable.

  • You tried to run a query after the connection to the server has been closed.

    Solution: A logic error in the application should be corrected.

  • Host name lookups failed (e.g. DNS server issue), or server has been started with --skip-networking option.

    Another possibility is that your firewall blocks the MySQL port (e.g. 3306 by default).

  • The running thread has been killed, so retry again.

  • You have encountered a bug where the server died while executing the query.

  • A client running on a different host does not have the necessary privileges to connect.

  • And many more, so learn more at: B.5.2.9 MySQL server has gone away.

For further details, please check your MySQL or system logs (e.g. /var/log/messages).

To debug MySQL server or client, please check: 26.5 Debugging and Porting MySQL.


In case you’re trying to import the database from the file using drush or mysql command, you can:

  • Add a force option (-f) for mysql to proceed and execute rest of the queries.

    This is useful if the database has some large queries related to cache which are large, but not relevant anyway.

    Using drush, try: cat foo.sql | $(drush sqlconnect) -f

  • Try applying --max-allowed-packet option for mysql with smaller values.

  • Increase max_allowed_packet and wait_timeout in your server config (e.g. ~/.my.cnf).

  • Dump the original database again by using --skip-extended-insert option to break down the large queries. Then import the file again.


See also: ERROR 2006 (HY000): MySQL server has gone away

answered Jun 7, 2016 at 14:57

kenorb's user avatar

kenorbkenorb

13.8k10 gold badges93 silver badges159 bronze badges

The answer that @Clive gives normally is the case, but there can be an additional cause, especially with node add forms.

Node add forms typically are big, and processing them can use a lot of memory (especially if there is any image processing during the save, like with the cropping modules). If the server runs out of memory, the mysqld process may get killed off which results in the same «gone away» message.

The clue is to look in the server logs. On a CentOS machine, you may see the following entry in /var/log/messages

Jan 1 00:00:00 servername kernel: Out of memory: Kill process XXXX
(mysqld) score XXX or sacrifice child
Jan 1 00:00:00 servername
kernel: Killed process XXXX, UID XX, (mysqld) total-vm:XXXkB,
anon-rss:XXXkB, file-rss:XXkB

The solution here is to either add more RAM, or add/increase swap.

answered May 7, 2015 at 14:40

mpdonadio's user avatar

mpdonadiompdonadio

37.9k8 gold badges87 silver badges141 bronze badges

I’ve had great success in fixing the 2006 MySQL server has gone away error with the following Drupal module:

Asynchronous Prefetch Database Query Cache

Just follow the installation instructions, which requires adding a few lines of code to settings.php and then visit admin/reports/status and apply advice given.

Most times, just by enabling the module and adding code to settings.php the error goes away straight away.

answered Dec 23, 2019 at 9:14

bmunslow's user avatar

bmunslowbmunslow

3712 silver badges10 bronze badges

1

The MySQL server has gone away error, which means that the MySQL server (mysqld) timed out and closed the connection. By default, MySQL will close connections after eight hours (28800 seconds) if nothing happens. However, in some cases, your web host, DBA, or app developer may have decreased this timeout setting, as discussed below.

MySQL server has gone away, can be a frustrating error to solve. This is partly because, to solve this error, sometimes the solution involves multiple layers, application, or service config changes. This article includes solutions I’ve seen for this MySQL server general error. If you’ve found a solution not listed or linked to on this page, please send me a note or leave a comment.

MySQL server has gone away

MySQL server has gone away error log examples.

Keep in mind that this error can be logged in a few ways, as listed below. In addition, at times, the error is only an indication of a deeper underlying issue. Meaning the error could be due to a problem or bug in your connecting application or remote service. In this case, you need to check ALL related error logs with the same timestamp to determine whether another issue may be to blame. Application Performance Monitoring solutions and PHP Stack trace tools can be of help. With this in mind, here are error log examples of the MySQL server has gone away error:

General error: 2006 MySQL server has gone away
Error Code: 2013. Lost connection to MySQL server during query
Warning: Error while sending QUERY packet
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

Sponsored: Datadog – View query metrics and explain plans from all of your databases in a single place.
Datadog database metrics
Datadog is a unified monitoring, analytics, and security platform that offers end-to-end monitoring for all of your databases, including MySQL, PostgreSQL, and more! Quickly pinpoint costly, slow queries and troubleshoot performance issues faster with key database metrics and patterns in one place. Easily search, compare, and filter your queries on execution plans to quickly identify areas for performance and cost improvements. Utilize our integrations for MySQL, PostgreSQL, SQL Server, and more to visualize key system performance metrics on an out-of-the-box dashboard alongside query and host-level metrics. Datadog Database Monitoring is closely integrated with the rest of the Datadog platform; further improve your Database performance with other key features such as SLO tracking, monitors & alerts, Security Monitoring, and more!

Cost: Free plan, or starting at $70.

MySQL wait_timeout

The reason for MySQL server has gone away error is often because MySQL’s wait_timeout was exceeded. MySQL wait_timeout is the number of seconds the server waits for activity on a non-interactive connection before closing it. You should make sure the wait_timeout is not set too low. The default for MySQL wait_timeout is 28800 seconds. Often, it gets lowered arbitrarily. That said, the lower you can set wait_timeout without affecting database connections, can be a good sign of MySQL database efficiency. Also, check the variables: net_read_timeoutnet_write_timeout and interactive_timeout. Adjust or add the following lines in my.cnf to meet your requirements:

wait_timeout=90
net_read_timeout=90
net_write_timeout=90
interactive_timeout=300
connect_timeout=90

MySQL connect timeout in PHP config.

Have a look at your php.ini config file. You’ll find MySQL configuration options. Make sure the mysql.connect_timeout setting isn’t set lower than MySQL wait_timeout, discussed above. The PHP option mysql.connect_timeout is not only used for connect timeout. It’s also when waiting for the first response from the MySQL server. Try increasing mysql.connect_timeout to match or exceed your MySQL wait_timeout and make sure that mysql.allow_persistent is on (default = enabled).

mysql.connect_timeout=90
mysql.allow_persistent=1

IMPORTANT: Read first about PHP Persistent Database Connections to understand the benefits and caveats.

Also, adjust PHP’s default_socket_timeout. For example, a PHP script could be running a slow query. Creating a wait that utilizes the default_socket_timeout. Eventually, it quits with the “MySQL server has gone away” error. Before you send hate mail, please read here first. Here’s an excerpt:

“PHP, by default, sets a read timeout of 60s for streams. This is set via php.ini, default_socket_timeout. This default applies to all streams that set no other timeout value. mysqlnd does not set any other value and therefore connections of long running queries can be disconnected after default_socket_timeout seconds resulting in an error message 2006 – MySQL Server has gone away.”

default_socket_timeout=90

To be throughout, also adjust max_execution_time and max_input_time still in php.ini, if necessary. If PHP’s execution time is longer than max_execution_time, then MySQL server might disconnect.

max_execution_time = 90
max_input_time = 90

MySQL max_allowed_packet

max_allowed_packet is the maximum size of one packet. The default size of 4MB helps the MySQL server catch large (possibly incorrect) packets. As of MySQL 8, the default has been increased to 16MB. If mysqld receives a packet that is too large, it assumes that something is wrong and closes the connection. To fix this, you should increase the max_allowed_packet in my.cnf, then restart MySQL. The max for this setting is 1GB. For example:

max_allowed_packet = 512M

MySQL innodb_log_file_size

You may need to increase the innodb_log_file_size MySQL variable in your my.cnf configuration. MySQL’s innodb_log_file_size should be 25% of innodb_buffer_pool_size (if possible, no less than 20%). Remember that the larger this value, the longer it will take to recover from a database crash. (Source: Phpmyadmin Advisor)

This means for example: if your buffer pool size is set to innodb_buffer_pool_size=16G and your innodb_log_files_in_group setting is still set to the recommended default of 2 files (innodb_log_files_in_group=2), then your innodb_log_file_size should be set to 2G. This will create two (2) log files at 2GB each, which equals 25% of innodb_buffer_pool_size=16G.

WARNING: You must stop MySQL server in order to change innodb_log_file_size or innodb_log_files_in_group. If you don’t, you risk catastrophe! (Read: MySQL Log Redo instructions.)

Other causes of MySQL server has gone away

Remote MySQL connections

Remember earlier I mentioned that the error, at times, is only an indication of a deeper underlying issue. For example, remote MySQL connections to 3rd party services. Using a 3rd party payment processing plugin for osCommerce, Magento, etc.

MySQL database charset and collation

Changing default database charset to latin1 and default collation to latin1_general_ci seemed to have solved MySQL server has gone away for some.

Exceeding MySQL max_connections setting

Max_connections set the maximum permitted number of simultaneous client connections. Be careful with this setting!! Exhaustion of memory and other resources can occur when set too large and scheduling overhead also increases. As a guide, set max_connections to approximately double the previous number of maximum simultaneous client connections. E.g., if after a month of uptime, the maximum simultaneous client connections were 114, then set to max_connections=250. Before you go crazy with this setting, please read: How MySQL Handles Client Connections.

Still unresolved? See MySQL’s help page.

Oracle has put together a nice self-help page for MySQL server has gone away errors. On that page, they also suggest that you make sure MySQL didn’t stop/restart during the query. Excerpt:

“You can check whether the MySQL server died and restarted by executing mysqladmin version and examining the server’s uptime. If the client connection was broken because mysqld crashed and restarted, you should concentrate on finding the reason for the crash.”

# mysqladmin version
mysqladmin Ver 9.1 Distrib 10.1.40-MariaDB, for Linux on x86_64
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Server version 10.1.40-MariaDB
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/lib/mysql/mysql.sock
Uptime: 20 days 11 hours 49 min 40 sec

Threads: 5 Questions: 1030744326 Slow queries: 3343 Opens: 3585 Flush tables: 1 Open tables: 2564 Queries per second avg: 582.150
# mysqladmin status
Uptime: 1770590 Threads: 4 Questions: 1030752268 Slow queries: 3343 Opens: 3585 Flush tables: 1 Open tables: 2564 Queries per second avg: 582.151

I hope this helps!


Related articles:

  • MySQL Performance Tuning: Tips, Scripts and Tools
  • Tuning MySQL: my.cnf, avoid this common pitfall!
  • MySQL Performance: Stop hoarding. Drop unused MySQL databases

Published: June 7th, 2019 | Last updated: Nov 10th, 2022

Tags: apm, linux, mariadb, mysql, performance, server, sysadmins

Аватар пользователя GarikHG


11 октября 2012 в 2:20


PDOException: SQLSTATE[HY000]: General error: 2006 MySQL

Additional uncaught exception thrown while handling exception.

Оригинальный
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = ‘default’; Array ( [:language] => sv [:source] => No tokens available. [:context] => ) in locale() (line 676 of /home/…/modules/locale/locale.module).

Дополнительный
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = ‘default’; Array ( [:language] => sv [:source] => %type: !message in %function (line %line of %file). [:context] => ) in locale() (line 676 of /home/…/modules/locale/locale.module).

Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 203 of /home/…/includes/session.inc)

Эта проблема — «MySQL server has gone away» — может случиться, если запрос, отправить на сервер MySQL является слишком большой. В самом деле, для меня проблема Решено, когда я поднял в MySQL max_allowed_packet настройку 1М (по умолчанию) до 32 млн. в моей my.cnf:

Оригинальный
# The MySQL server
[wampmysqld]
port = 3306
socket = /tmp/mysql.sock
key_buffer = 16M
max_allowed_packet = 1M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
basedir=d:/wamp/bin/mysql/mysql5.5.16
log-error=d:/wamp/logs/mysql.log
datadir=d:/wamp/bin/mysql/mysql5.5.16/data

Решения

настройки WAMP SERVER my.ini
# The MySQL server
[wampmysqld]
port = 3306
socket = /tmp/mysql.sock
key_buffer = 16M
max_allowed_packet = 64M
table_cache = 64
sort_buffer_size = 1024K
net_buffer_length = 16K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 32M
basedir=c:/wamp/bin/mysql/mysql5.5.24
log-error=c:/wamp/logs/mysql.log
datadir=c:/wamp/bin/mysql/mysql5.5.24/data

max_allowed_packet = 32M

  • Drupal7
  • Предлагаю решение
  • FAQ

“MySQL Server has gone away” is a cryptic error that can be hard to troubleshoot (look at all the various responses on Stack Overflow!) Many problems can cause this error; I would like to document one specific case. In this example, the client is a PHP app using the Phalcon framework:

[Mon, 09 Apr 18 03:34:08 -0400][ERROR]  SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /path/to/ModelBase.php:
Stack trace:
#0 [internal function]: PDOStatement->execute()
...
#17 {main}


This error can be tricky to troubleshoot. I looked in three logs:

    1. MySQL error log on the server
      1. MariaDB:
        sudo journalctl -u mariadb
      2. MySQL/Percona:
        sudo journalctl -u mysql
    2. MySQL slow query log on the server (may not be enabled on your server)
    3. MySQL client log

No errors or slow queries happened on the MySQL server at the time that it “went away;” clearly the server was not actually crashing or dying.
The key to troubleshooting this error is to look at the other errors that are logged before and/or after it on the SQL client. The key phrase is “Got a packet bigger than ‘max_allowed_packet’ bytes”, which means that the client is sending a single chunk of data that’s greater than what the SQL server is configured to accept. In our case, such an error should not have happened, because the PHP application “batches” data for processing. However, by following the stacktrace, we discovered that a developer was also writing raw, un-batched data to the DB for debugging purposes. As soon as we disabled that process, the errors stopped.

[Mon, 09 Apr 18 03:34:08 -0400][ERROR]  SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes (a3b0fb66)
(a3b0fb66) exception 'AppExceptionUpdateException' with message 'SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes' in :
Stack trace:
#0 (line): AppDatabaseDbUtils::directDbCore('INSERT INTO imp...', 'query', '')
#1 (line): AppDatabaseDbUtils::directDb('INSERT INTO imp...', 'query', '')
...
#17 {main}

Finally, this error also occurred every time the other two occurred, though I’m not sure of its significance:

[Mon, 09 Apr 18 03:34:08 -0400][ERROR]  FAILED TO DB LOG!: Error while sending QUERY packet. PID=30216
#0 [internal function]: {closure}(2, 'Error while sen...', '/var/www/html/a...', 954, Array)
#1 [internal function]: PDOStatement->execute()
#2 [internal function]: PhalconDbAdapterPdo->executePrepared(Object(PDOStatement), Array, Array)
#3 [internal function]: PhalconDbAdapterPdo->execute('INSERT INTO `ex...', Array, Array)
#4 [internal function]: PhalconDbAdapter->insert('exceptions', Array, Array, Array)
...
#22 {main}

Понравилась статья? Поделить с друзьями:
  • Pdoexception sqlstate hy000 general error 1215 cannot add foreign key constraint
  • Pdo statement error
  • Pdo last error
  • Pdo fetch general error
  • Pdo execute fatal error