/ Published in: SQL
Cronjob and PHP examples below
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
## CODE mysql -u<username> -p<password> <DATABASE name> -e "OPTIMIZE TABLE `table1`, `table2`, `etc`;" ## NOTE: Something LIKE this may help. Dan W made this script FROM his own ## knowledge, AND a little bit OF research ON Google. This script can ONLY ## OPTIMIZE one DATABASE. IF you need TO OPTIMIZE more than one, you will ## have TO ADD a few more LINES OF code IN there. ## CODE <?php $server = 'localhost'; $username = 'mysql_username'; $password = 'mysql_password'; $database = 'mysql_database_name'; ### connects TO the DATABASE, OR dies WITH error $connection = mysql_connect($server,$username,$password); IF (!$connection) { die( mysql_error() ); } ### selects the db OF choice, OR dies WITH error $db_selection = mysql_select_db($database, $connection); IF (!$db_selection) { die( mysql_error() ); } ### selects ALL TABLES IN the db OF choice, OR dies WITH error $alltables = mysql_query("SHOW TABLES") OR die ( mysql_error() ); ### loops through ALL OF the TABLES AND optimizes each, OR dies WITH error while ( $table = mysql_fetch_array($alltables) ) { mysql_query("OPTIMIZE TABLE `".$table."`") OR die( mysql_error() ); } ### closes the mysql connection mysql_close($connection); ?> ## Be sure TO edit the VARIABLES at the top TO the VALUES that are ## appropriate FOR you. WHEN you GO TO run your cron job, again just ## do "php /full/path/to/script.php" AND since optimizing TABLES may ## LOCK down your DB FOR a SECOND, run the script at a TIME WHEN you ## don't expect traffic.
URL: http://forums.asmallorange.com/topic/12948-cron-job-to-optimize-database/