Kirya [.net]

Last updated: May 25, 2008

Optimize MySQL tables

If you have a database driven site and you want to optimize MySQL tables then this small PHP script is perfect. It goes through all the tables in all MySQL databases the user has access to and does table optimization on each one using the MySQL Optimize Table syntax.

#!/usr/bin/php
<?php
$server = "localhost";
$user = "mysql-user";
$pwd = "password";
 
$link = mysql_connect($server, $user, $pwd);
if (!$link) {
  die('Could not connect: ' . mysql_error());
}
 
$q= mysql_query("SHOW DATABASES") or die(mysql_error());
 while ($dbName = mysql_fetch_array($q)) {
   if ($dbName[0] != "information_schema") {
     echo " + Selecting " . $dbName[0] . "\n";
     $db_selected = mysql_select_db($dbName[0], $link);
        if (!$db_selected) {
        die ('Can\'t use $dbName[0] : ' . mysql_error());
     }
 
     $alltables = mysql_query("SHOW TABLES") or die(mysql_error());
 
     while ($tableName = mysql_fetch_array($alltables)) {
        echo "   - Optimizing " . $tableName[0] . "\n";
        mysql_query("OPTIMIZE TABLE `".$tableName[0]."`") or die(mysql_error());
     }
   } else {
      echo " + Skipping " . $dbName[0] . "\n";
   }
}
 
mysql_close($link);
 
?>

You can set a daily cronjob to launch this script automatically. Note that the databases are locked while being optimized!

Remember to set restricitve read permissions to this script (chmod 700 mysql-opt.php) as it contains sensible data!

About

You will find here some information about me and my different projects. I am involved in several open source projects, and try to promote Free software. This site is thus mainly dedicated to Free Software use on GNU/Linux systems. Please do not hesitate to contact me for any comments on this site.