Created
November 28, 2023 22:19
-
-
Save nightkingdoms/5f4326f245041c401a6ee30125611b00 to your computer and use it in GitHub Desktop.
Run with `php kill_long_processes.php` on command line to kill long running query processes in MySQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$config = [ | |
'db' => [ | |
'host' => '', | |
'username' => '', | |
'password' => '', | |
'database' => '', | |
], | |
'max_time' => 300, // in seconds | |
]; | |
// Create MySQL connection | |
$mysqli = new mysqli($config['db']['host'], $config['db']['username'], $config['db']['password'], $config['db']['database']); | |
// Check connection | |
if ($mysqli->connect_error) { | |
die("Connection failed: " . $mysqli->connect_error); | |
} | |
// Query to find long-running queries | |
$sql = "SELECT ID FROM information_schema.processlist WHERE `TIME` > " . $config['max_time']; | |
// Execute query | |
if ($result = $mysqli->query($sql)) { | |
while ($row = $result->fetch_assoc()) { | |
$processId = $row['ID']; | |
// Kill the query | |
$killQuery = "KILL $processId"; | |
if (!$mysqli->query($killQuery)) { | |
echo "Error killing query $processId: " . $mysqli->error . "\n"; | |
} else { | |
echo "Killed query $processId\n"; | |
} | |
} | |
$result->free(); | |
} else { | |
echo "Error: " . $mysqli->error . "\n"; | |
} | |
// Close connection | |
$mysqli->close(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment