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

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

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