When performing bulk operations, such as inserting hundreds of records into a MySQL database, you may encounter the following error:
[PDOException] SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
This error typically arises due to a timeout issue where the MySQL server disconnects your connection after a set period of inactivity. To resolve this issue, focus on adjusting two primary settings:
The wait_timeout setting determines the duration (in seconds) that MySQL will wait before terminating an inactive connection. By default, this value is set to a relatively low 30 seconds on shared hosting environments.
To increase the wait_timeout, issue the following query at the start of your operation:
SET session wait_timeout=28800;
This command sets the wait_timeout to 28800 seconds, which is approximately 8 hours.
In some cases, you might also need to adjust the interactive_timeout setting. This setting specifies the number of seconds before MySQL terminates an interactive connection.
To modify interactive_timeout, execute the following query after adjusting wait_timeout:
SET session interactive_timeout=28800;
To confirm that the settings have been successfully modified, you can execute the following query before and after making the changes:
<code class="php">$results = $db->query("SHOW VARIABLES LIKE '%timeout%'", TRUE);</code>
While increasing the timeout settings can resolve the immediate issue, it's important to consider the following:
The above is the detailed content of How to Fix the \'General Error: 2006 MySQL Server Has Gone Away\' During Bulk Operations?. For more information, please follow other related articles on the PHP Chinese website!