Skip to content

Instantly share code, notes, and snippets.

@nightkingdoms
Created November 28, 2023 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nightkingdoms/5f4326f245041c401a6ee30125611b00 to your computer and use it in GitHub Desktop.
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
<?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