MySQL server has gone away

I came through this error when i run the mailscript.php file via cron job (I have send 4000 newsletter to registered user with 5 second interval for each mail, using php script with cron).

This occurred due to mysql time out was set 10 sec, after 10 sec mysql server got disconnected which caused the issue.

Why it happened & Why are we getting this error from mysql ?

Due to mysql server connection got closed automatically a certain seconds which is mention in my.cnf file.

Most of them advise to use “solution-1” but its not a permanent solution, from my experience using “solution-2” to gave the permanent solution

Go to >> nano /etc/my.cnf

By default configuration on mysql server
----------------------------------------
[mysqld]
port	 = 3306
socket	 = /tmp/mysql.sock
skip-locking
key_buffer = 384M
max_allowed_packet = 1M
table_cache = 512
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size = 32M
wait_timeout=10
---------------------------------------

1) Solution-1: Not permanent solution

Change "max_allowed_packet = 1M" to "max_allowed_packet = 32M"
Change "wait_timeout=10 sec" to "wait_timeout=28800 sec"

After done this, don’t forget to restart the mysql service to take effect the changed settings.

# service mysql restart

2) Solution-2: permanent solution

Change the mysql connection type on your php script

Change the mysql connection type from "mysql_connect()" to "mysql_pconnect()"
Also close the mysql connection at the end of the script "mysql_close()"

mysql_pconnect() >> the connection to the SQL server will not be closed unless and until the execution of the script ends.

Note: If you have dedicated or vps server you can able to access my.cnf file but in shared customer is not possible to do it. So permanent & better one is Solution-2.

Hope this article was useful for you. Kindly provide your valuable feedback/comments in the commenting section.

Stay tuned with us !!

Magesh Maruthamuthu

Love to play with all Linux distribution

You may also like...