Thursday, July 30, 2009

用 PHP 查詢 MySQL Table 使用空間

要查詢 MySQL 資料表所用的空間,雖然資料表是用 MyISAM 的話,可以直接用 ls 指令知道,但這個方法不可以用在 InnoDB 資料表上面。

要計算資料表的容量,可以供用 MySQL 語句 "SHOW TABLE STATUS" 實現,然後將回傳的 Data_length 加 Index_length 即可。以下程式會擷取資料庫內所有資料表的使用空間:

PHP:
  1. $db_link = mysql_connect("localhost", "db_username", "db_password");
  2. mysql_select_db("db_name", $db_link);
  3. $result = mysql_query("SHOW TABLE STATUS");
  4. while($rows = mysql_fetch_array($result)){
  5. $total_size = $rows['Data_length'] + $rows['Index_length'];
  6. // return table size by KB or MB
  7. if($total_size <1048576){
  8. $total_size = $total_size / 1024;
  9. }else{
  10. $total_size = $total_size / 1024 / 1024;
  11. }
  12. $tables[$rows['Name']] = sprintf("%.2f", $total_size);
  13. }
  14. print_r($tables);

No comments:

Post a Comment