View Single Post
  #3  
Old 05-04-2005, 07:38 AM
 
NuAlpha NuAlpha is offline
 

X-Adept
  
Join Date: Aug 2003
Location: US
Posts: 598
 

Default

Here is an update of the code. Noticed a potential security issue. This fix might disable the script on some people's servers so if it does and you have another solution, then just remove the condition. The condition if (empty($_SERVER['REMOTE_ADDR']) && empty($_SERVER['SERVER_ADDR'])) below is meant to prevent anyone but the cronjob from running the script.

I have also added the ability to optimize more than one database. This is useful if, for instance, you have your stie stats recorded to a seperate database.

Code:
<?php # $Id: db_optimizer.php,v 1.2.3 2005/01/05 15:35:20 nualpha Exp $ ############################################################################## ## ## Database Table Optimizer ## ## ############################################################################## ## Optimize all database tables once every 24 hours through a cronjob. ## ## If a table is damaged, this script will attempt to repair it. ## ############################################################################## ## Initially Created: 6/8/2004 # Ensure the script execution request is by the server. if (empty($_SERVER['REMOTE_ADDR']) && empty($_SERVER['SERVER_ADDR'])) { # Define Constants define('ERROR_LOG', '/absolute-path-to-your-log-directory/db_optimization_errors.html'); define('DB_LINK', mysql_connect('server_address','sql_login','sql_password')); # Define databases to be optimized. $db_name = array('list_of_comma_seperated','databases_here'); foreach ($db_name as $db) { mysql_select_db($db, DB_LINK); # Get all tables in the database. $result = mysql_list_tables($db); $sim_tab = ''; // Simulate tab with HTML non-breaking spaces. # Begin table optimizations. for ($i=0; $i < mysql_num_rows($result); $i++) { $current_table = mysql_tablename($result, $i); $opt_table = mysql_query('OPTIMIZE TABLE '.$current_table, DB_LINK) or error_log("Couldn't optimize the '$current_table' table! ". $sim_tab.'MySQL said: '.mysql_error()." \n",3,ERROR_LOG); if (!$opt_table && preg_match("/'(\S+)\.(MYI|MYD)/",mysql_error(), $damaged_table)) { # Repair broken indexes. mysql_query('REPAIR TABLE '.$damaged_table[1], DB_LINK) or error_log("Couldn't repair the '$current_table' table! ". $sim_tab.'MySQL said: '.mysql_error()." \n",3,ERROR_LOG); $opt_table = null; # Try to optimize the table again. $opt_table = mysql_query('OPTIMIZE TABLE '.$current_table, DB_LINK) or error_log("Couldn't optimize the '$current_table' table after trying to repair it! ". $sim_tab.'MySQL said: '.mysql_error()." \n",3,ERROR_LOG); } } } } ?>
__________________
X-Cart Pro 4.5.5 Platinum
X-Payments 1.0.6
PHP 5.3.14
MySQL 5.1.68
Apache 2.2.23
Reply With Quote