Home >Backend Development >PHP Tutorial >apache php mysql PHP method to clear MySQL dead connections
The example in this article describes the method of clearing MySQL dead connections in PHP. I share it with you for your reference. The details are as follows:
The main manifestation of the connection situation is that there are too many Sleep connections, and the Time is very long, occupying all the available connections, so that other users can no longer connect to the database. I began to consider adjusting the MySQL database parameters, but changed many parameters and still did not solve the problem. So I thought of a more ruthless way to write a php script and execute it every 2 minutes. If a dead connection is found (more than 120 seconds), kill it. In this way, some programs will no longer kill the database server. The following is Kill Small program for dead connection:
kill-mysql-sleep-proc.php:
define('MAX_SLEEP_TIME',120); $hostname="localhost"; $username="root"; $password="password"; $c $result=mysql_query("SHOWPROCESSLIST",$connect); while($proc=mysql_fetch_assoc($result)){ if($proc["Command"]=="Sleep"&&$proc["Time"]>MAX_SLEEP_TIME){ @mysql_query("KILL".$proc["Id"],$connect); } } mysql_close($connect); ?>
Change $password in it to your actual database password, and the time of dead connection can also be modified. Then just add the scheduled task. For example, use the crontab-e command to add:
*/2****php/usr/local/sbin/kill-mysql-sleep-proc.php
You can check and clear dead connections in the database every 2 minutes
Readers who are interested in more PHP-related content can check out this site's special topic: "php+ Summary of MySQL Database Programming Skills", "Summary of PHP Database Operation Skills Based on PDO", "Summary of PHP Operations and Operator Usage", "Summary of PHP Network Programming Skills", "Introduction Tutorial on PHP Object-Oriented Programming", "php String (string) usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will be helpful to everyone in PHP programming.
The above introduces the method of apache php mysql PHP to clear MySQL dead connections, including the content of apache php mysql. I hope it will be helpful to friends who are interested in PHP tutorials.