PHP+MySQL如何统计数据库容量?

想知道已经用了多少数据库空间

用php代码怎么写?

要想知道每个数据库的大小的话,步骤如下:
1、进入information_schema 数据库(存放了其他的数据库的信息)
use information_schema;

2、查询所有数据的大小:
select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables;

3、查看指定数据库的大小:
比如查看数据库home的大小
select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='home';

4、查看指定数据库的某个表的大小
比如查看数据库home中 members 表的大小
select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='home' and table_name='members';

php连接数据库服务器,然后选择使用的数据库名称为information_schema,然后执行查询就行了。看你问的这个问题应该不会不知道用php访问数据库吧。

如果你权限不够的话可能只能对特定的数据库的信息进行查询。追问

完整的PHP代码如何写?

追答

  亲,给你代码但是不保证能用啊,谁知道你的数据库怎么配置的
  <?php
  $conn = mysql_connect('localhost', 'root', '');
  mysql_select_db('information_schema');
  $target_db_name = 'test';
  $sql = "select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='{$target_db_name}'";
  $result = mysql_query($sql);
  $row = mysql_fetch_row($result);
  print_r($row);

追问

$db_host = 'localhost';//数据库主机地址

$db_user = 'root'; //帐号
$db_pass = 'root'; //密码
$db_name = 'db_name'; //数据库名
$db_info = 'db_info'; //数据表

追答

<?php
$db_host = 'localhost';//数据库主机地址
$db_user = 'root'; //帐号
$db_pass = 'root'; //密码
$db_name = 'db_name'; //数据库名
$db_info = 'db_info'; //数据表

  $conn = mysql_connect($db_host, $db_user, $db_pass);
  mysql_select_db('information_schema');
  $target_db_name = $db_name;
  $sql = "select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='{$target_db_name}'";
  $result = mysql_query($sql);
  $row = mysql_fetch_row($result);
  print_r($row);
  $sql = "select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='{$target_db_name}' and table_name='{$db_info}'";
  $result = mysql_query($sql);
  $row = mysql_fetch_row($result);
  print_r($row);

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-23
PHP 最主要就是执行SQL, 你在数据库知道怎么获取使用空间,那么Php代码就简单了。追问

完整的PHP代码如何写?
$db_host = 'localhost';//数据库主机地址
$db_user = 'root'; //帐号
$db_pass = 'root'; //密码
$db_name = 'db_name'; //数据库名
$db_info = 'db_info'; //数据表