Sunday, November 22, 2009

Finding Database Size using php & mysql

The dbsize of mysql can be retrieved using the query "show table status'.

Follow the steps to find the DB size
Step 1:
Getting connection with the databse
<?php

$db = mysql_connect("hostname", "username","password"); //getting the mysql db connection by passing correct hostname,username and passowrd
mysql_select_db("dbname",$db); //there we pass the db name for which we want the size to be calculated. This is like calling "use dbanme";
?>
Step 2:
The dbsize is the total of Index_length and Data_lenth columns of all the tables present in the database selected.
We will find the size with the below function


<?php
{
$sql = "SHOW TABLE STATUS";
$result = mysql_query($sql); // This is the result of executing the query
while($row = mysql_fetch_array($result))// Here we are to add the columns 'Index_length' and 'Data_length' of each row
{
$total = $row['Data_length']+$row['Index_length'];
}
echo($total); // here we print the file size in bytes
}
?>