mysql server has gone away php

Как исправить ошибку MySQL Server Has Gone Away

Ошибка MySQL Server Has Gone Away (error 2006) может возникнуть в двух случаях:

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

Решение с внесением изменений в файл /etc/mysql/my.cnf.

ВАРИАНТ 1 — Таймаут соединения С БД

Программный код может делать запрос в базу данных, который обрабатывается больше максимального времени выполнения запроса, установленного в конфигурационном файле. При этом срабатывает ограничение на время ожидания в сессии.

Лучше всего выяснить почему такие запросы имеют место и оптимизировать их, но для того чтобы получить мгновенный результат нужно увеличить значение параметра wait_timeout. Значение задается в секундах и не может быть более 28800.

wait_timeout = 1000

После внесения любых изменений в конфигурационный файл перезапускаем MySQL

ВАРИАНТ 2 — СЛИШКОМ Большой пакет

Несколько другая ситуация имеет место когда сервер отклоняет пакет из-за его слишком большого размера (или в случае если сервер не может распознать пакет по той или иной причине). В логи при этом пишутся точно такие же сообщения.

Решение в этом случае практически такое же — необходимо скорректировать значение одной переменной в конфигурационном файле.

[mysqld]
max_allowed_packet = 96M

В примере задан максимальный размер пакета, который сервер не будет отвергать — 96 Мб. Устанавливать слишком большие значения не стоит.

Источник

PHP: MySQL server has gone away

I know this question has been asked numerous times but I’ve tried everything.

I have a PHP script that iterates through thousands of images, performs resizing if necessary and then inserts into the database.

I’m getting this error message:

Warning: mysql_query() [function.mysql-query]: MySQL server has gone away in C:\Utilities\server\htdocs\newGen\index.php on line 105

Warning: mysql_query() [function.mysql-query]: Error reading result set’s header in C:\Utilities\server\htdocs\newGen\index.php on line 105

I’m using Xampplite and so some parts of the php.ini are missing that others have used to solve the problem because they’re not using the lite version.

I’m certain the problem is not timeouts. While the script will run for several minutes it skips over images that have already been processed and so I quickly get the error message within about 10 seconds. Maybe this has something to do with max table size? I can’t find anything in my php.ini that controls this.

All help is greatly appreciated, I’ve been going at this for hours now.

Here is the code at the 105 mark, it’s the query:

As you can see by the comments I tried PDO with this and got the same error, foolishly I thought going back to mysql_ commands would help.

If it’s of any help the script complains at the same image every time, yet each image is only ever a few tens of kilobytes and a couple hundred at the most.

Источник

Ошибка 2006: MySQL server has gone away

Эта ошибка означает, что MySQL сервер запущен, но он отказывает вам в соединении. Это может произойти по нескольким причинам. Самых основных и часто встречающихся причин три: сервер перегружен, и у вас истекло время ожидания ответа, ваш клиент отправил слишком большой пакет или сервер был не до конца проинициализирован.

В этой небольшой статье мы рассмотрим более подробно, почему возникает ошибка 2006: MySQL server has gone away, а также — как её исправить.

Как исправить MySQL server has gone away

Такую ошибку вы можете увидеть во время подключения к базе данных с помощью PHP, консольного клиента или, например, в PhpMyAdmin:

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

1. Истекло время ожидания

Как я уже писал выше, одной из причин может быть таймаут ожидания соединения. Возможно, сервер баз данных перегружен и не успевает обрабатывать все соединения. Вы можете подключиться к серверу с помощью консольного клиента, если вам это удастся, и попытаться выполнить какой-либо запрос, чтобы понять, действительно ли запросы выполняются слишком долго. Если это так, можно оптимизировать производительность MySQL с помощью скрипта MySQLTuner.

В большинстве случаев надо увеличить размер пула движка InnoDB с помощью параметра innodb_buffer_pool_size. Какое значение лучше поставить, можно узнать с помощью указанного выше скрипта. Например, 800 мегабайт:

sudo vi /etc/mysql/my.cnf

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

Есть и другой путь решения этой проблемы. Если такая скорость обработки запросов считается нормальной, можно увеличить время ожидания ответа от сервера. Для этого измените значение параметра wait_timeout. Это время в секундах, на протяжении которого надо ждать ответа от сервера. Например:

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

После любых изменений не забудьте перезапустить MySQL сервер:

sudo systemctl restart mysql

sudo systemctl restart mariadb

2. Слишком большой пакет

Если ваш клиент MySQL создаёт слишком большие пакеты с запросами к серверу, это тоже может стать причиной такой ошибки. Максимально доступный размер пакета можно увеличить с помощью параметра max_allowed_packet. Например:

sudo vi /etc/mysql/my.cnf

Обратите внимание, что если вы из своей программы отправляете большие пакеты, то, скорее всего, вы делаете что-то не так. Не надо генерировать запросы к MySQL с помощью циклов for. SQL — это отдельный язык программирования, который многое может сделать сам, без необходимости писать очень длинные запросы.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

3. Сервер неверно проинициализирован

Такая проблема может возникать при разворачивании контейнера MySQL или MariaDB в Docker. Дело в том, что на первоначальную инициализацию контейнера нужно много времени: около нескольких минут. Если вы не дадите контейнеру завершить инициализацию, а остановите его и потом снова запустите, то база данных будет всегда возвращать такую ошибку.

Вам нужно полностью удалить данные контейнера с базой данных. Например, с помощью docker-compose:

docker rm mysql-container

Здесь mysql-container — это имя контейнера с базой данных. А затем надо удалить хранилище (volume) с некорректно проинициализированной базой. Сначала посмотрите список всех хранилищ:

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

Затем удалите нужное:

docker volume rm имя_хранилища

После этого можете снова запускать инициализацию приложения, только на этот раз дождитесь, пока сервер баз данных сообщит, что он готов, и вы сможете к нему подключиться.

Выводы

В этой небольшой статье мы рассмотрели, что значит ошибка MySQL Server has gone away, а также как её исправить на сервере или в контейнере Docker. Вы знаете ещё другие причины и решения этой проблемы? Пишите в комментариях!

Источник

MySQL error 2006: mysql server has gone away

I’m running a server at my office to process some files and report the results to a remote MySQL server.

The files processing takes some time and the process dies halfway through with the following error:

I’ve heard about the MySQL setting, wait_timeout, but do I need to change that on the server at my office or the remote MySQL server?

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

31 Answers 31

Note: Just create the line if it does not exist

Note: This can be set on your server as it’s running.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

I had the same problem but changeing max_allowed_packet in the my.ini/my.cnf file under [mysqld] made the trick.

now restart the MySQL service once you are done.

I used following command in MySQL command-line to restore a MySQL database which size more than 7GB, and it works.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

It may be easier to check if the connection and re-establish it if needed.

See PHP:mysqli_ping for info on that.

Message: MySQL server has gone away

I’ll assuming you are using PDO. If so then you would catch the PDO Exception, increment a counter and then try again if the counter is under a threshold.

If you have a query that is causing a timeout you can set this variable by executing:

Where 300 is the number of seconds you think the maximum time the query could take.

In MAMP (non-pro version) I added

Credits and more details here

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

There are several causes for this error.

MySQL/MariaDB related:

Example of my.cnf:

Server related:

Framework related:

How to debug it:

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

Just go to mysql server check its wait_timeout :

mysql> SHOW VARIABLES LIKE ‘wait_timeout’

mysql> set global wait_timeout = 600 # 10 minute or maximum wait time out you need

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

On windows those guys using xampp should use this path xampp/mysql/bin/my.ini and change max_allowed_packet(under section[mysqld])to your choice size. e.g

Again on php.ini(xampp/php/php.ini) change upload_max_filesize the choice size. e.g

Gave me a headache for sometime till i discovered this. Hope it helps.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

If you are using xampp server :

Change below parameter :

max_allowed_packet = 500M

innodb_log_file_size = 128M

This helped me a lot 🙂

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

I was getting this same error on my DigitalOcean Ubuntu server.

I tried changing the max_allowed_packet and the wait_timeout settings but neither of them fixed it.

It turns out that my server was out of RAM. I added a 1GB swap file and that fixed my problem.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

It was RAM problem for me.

I was having the same problem even on a server with 12 CPU cores and 32 GB RAM. I researched more and tried to free up RAM. Here is the command I used on Ubuntu 14.04 to free up RAM:

And, it fixed everything. I have set it under cron to run every hour.

And, you can use this command to check how much free RAM available:

And, you will get something like this:

In my case it was low value of open_files_limit variable, which blocked the access of mysqld to data files.

After I changed the variable to big value, our server was alive again :

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

If you are using the 64Bit WAMPSERVER, please search for multiple occurrences of max_allowed_packet because WAMP uses the value set under [wampmysqld64] and not the value set under [mysqldump], which for me was the issue, I was updating the wrong one. Set this to something like max_allowed_packet = 64M.

Hopefully this helps other Wampserver-users out there.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

This generally indicates MySQL server connectivity issues or timeouts. Can generally be solved by changing wait_timeout and max_allowed_packet in my.cnf or similar.

I would suggest these values:

wait_timeout = 28800

max_allowed_packet = 8M

It’s always a good idea to check the logs of the Mysql server, for the reason why it went away.

There is an easier way if you are using XAMPP. Open the XAMPP control panel, and click on the config button in mysql section.
mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

Now click on the my.ini and it will open in the editor. Update the max_allowed_packet to your required size.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

Then restart the mysql service. Click on stop on the Mysql service click start again. Wait for a few minutes. mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

Then try to run your Mysql query again. Hope it will work.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

MAMP 5.3, you will not find my.cnf and adding them does not work as that max_allowed_packet is stored in variables.

One solution can be:

Run the following query, it set max_allowed_packet to 7gb:

set global max_allowed_packet=268435456;

For some, you may need to increase the following values as well:

For Vagrant Box, make sure you allocate enough memory to the box

Increase the packet size.

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

The unlikely scenario is you have a firewall between the client and the server that forces TCP reset into the connection.

I had that issue, and I found our corporate F5 firewall was configured to terminate inactive sessions that are idle for more than 5 mins.

Once again, this is the unlikely scenario.

Path of these files in windows is

In these two files the value of this:

Then restart Wampserver.

To change phpmyadmin user name and password

You can directly change the user name and password of phpmyadmin through config.inc.php file

Here you can give new user name and password. After changes save the file and restart WAMP server.

I got Error 2006 message in different MySQL clients software on my Ubuntu desktop. It turned out that my JDBC driver version was too old.

This error happens basically for two reasons.

You can try this code below.

It mitigates the error whatever the reason behind it, especially for the second reason.

If it’s caused by low RAM, you either have to raise database connection efficiency from the code, from the database configuration, or simply raise the RAM.

I had the same problem in docker adding below setting in docker-compose.yml :

mysql server has gone away php. Смотреть фото mysql server has gone away php. Смотреть картинку mysql server has gone away php. Картинка про mysql server has gone away php. Фото mysql server has gone away php

What I did is I troubleshoot my database:

The solution that I thought of is to reimport the database. Good thing is I have a backup of this database. But I only dropped the problematic table, then import my backup of this table. That solved my problem.

My takeaway of this problem:

Источник

Mysql server has gone away php

This section also covers the related Lost connection to server during query error.

The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection. In this case, you normally get one of the following error codes (which one you get is operating system-dependent).

Error CodeDescription
CR_SERVER_GONE_ERRORThe client couldn’t send a question to the server.
CR_SERVER_LOSTThe client didn’t get an error when writing to the server, but it didn’t get a full answer (or any answer) to the question.

If you have a script, you just have to issue the query again for the client to do an automatic reconnection. This assumes that you have automatic reconnection in the client enabled (which is the default for the mysql command-line client).

Some other common reasons for the MySQL server has gone away error are:

You tried to run a query after closing the connection to the server. This indicates a logic error in the application that should be corrected.

A client application running on a different host does not have the necessary privileges to connect to the MySQL server from that host.

You have encountered a timeout on the server side and the automatic reconnection in the client is disabled (the reconnect flag in the MYSQL structure is equal to 0).

You are using a Windows client and the server had dropped the connection (probably because wait_timeout expired) before the command was issued.

The problem on Windows is that in some cases MySQL does not get an error from the OS when writing to the TCP/IP connection to the server, but instead gets the error when trying to read the answer from the connection.

It is also possible to see this error if host name lookups fail (for example, if the DNS server on which your server or network relies goes down). This is because MySQL is dependent on the host system for name resolution, but has no way of knowing whether it is working—from MySQL’s point of view the problem is indistinguishable from any other network timeout.

You may also see the MySQL server has gone away error if MySQL is started with the skip_networking system variable enabled.

Another networking issue that can cause this error occurs if the MySQL port (default 3306) is blocked by your firewall, thus preventing any connections at all to the MySQL server.

You can also encounter this error with applications that fork child processes, all of which try to use the same connection to the MySQL server. This can be avoided by using a separate connection for each child process.

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

If you want to create a bug report regarding this problem, be sure that you include the following information:

Indicate whether the MySQL server died. You can find information about this in the server error log. See Section B.3.3.3, “What to Do If MySQL Keeps Crashing”.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *