Friday, 10 August 2018

Optimize A MySQL Table Using PHP


In MySQL the OPTIMIZE TABLE can be used if you have made changes or have deleted large parts of the table.
Any deleted rows are kept behind the scenes in the server in order to allow the reuse of these spaces. The OPTIMIZE TABLE command reclaims the unused space and defragments the data file.
For a normal MyISAM table the OPTIMIZE command works in the following way.
  1. If the table has deleted or split rows, repair the table.
  2. If the index pages are not sorted, sort them.
  3. If the table's statistics are not up to date (and the repair could not be accomplished by sorting the index), update them.
You can do this automatically by using the following PHP code.
  1. // connect to database
  2. $con = mysql_connect("localhost","root","wibble");
  3. // select the correct database
  4. mysql_select_db("database");
  5. // get a list of the tables
  6. $alltables = mysql_query("SHOW TABLES;");
  7. // record the output
  8. $output = array();
  9. while($table = mysql_fetch_assoc($alltables)){
  10. foreach($table as $db => $tablename){
  11. $sql = 'OPTIMIZE TABLE '.$tablename.';';
  12. $response = mysql_query($sql) or die(mysql_error());
  13. $output[] = mysql_fetch_assoc($response);
  14. };
  15. };
  16. // print output
  17. print_r($output);
Here is a sample of what the output array contains
  1. [0] => Array
  2. (
  3. [Table] => database.table1
  4. [Op] => optimize
  5. [Msg_type] => status
  6. [Msg_text] => Table is already up to date
  7. )
  8. [1] => Array
  9. (
  10. [Table] => database.table2
  11. [Op] => optimize
  12. [Msg_type] => status
  13. [Msg_text] => OK
  14. )
Note that you don't need to run this command every time you do anything. You should only run this after a major data upheaval, or after a few months or weeks of usage.

0 comments:

Post a Comment