Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Get Size of a MySQL Database (0 Comments)
Admin: Posted Date: March 3, 2010

This simple tutorial will show you how to get the size of a MySQL database using PHP in just a few simple steps. First of you'll need my formatfilesize() function; for this script to work you will obviously need to connect to your MySQL database.

Get the size of a MySQL database with PHP

This simple tutorial will show you how to get the size of a MySQL database using PHP in just a few simple steps.

First of you’ll need my formatfilesize() function;(given at the end), for this script to work you will obviously need to connect to your MySQL database. Then add this line of code but replace “databasename” with the name of your database:

Set the database name

<?php

 $dbname = “databasename”;

 ?>

Now comes the fundamental part of the tutorial: computing the database size. It’s actually very simple – all we need to do is to go through each table in the database and add up the length of the data and the index:

Add up the index and data for each table

<?php

    mysql_select_db( $dbname );

    $result = mysql_query( “SHOW TABLE STATUS” );

    $dbsize = 0;

     while( $row = mysql_fetch_array( $result ) ) {  

     $dbsize += $row[ "Data_length" ] + $row[ "Index_length" ];

     }

 ?>

We now have the size of the databse in bytes sotred in the $dbsize variable. Now we just output it to a more user-friendly format using my formatfilesize() function:

Output the database size

 <?php

 echo “<p>The size of the database is ” . formatfilesize( $dbsize ) . “</p>”;

?>

 

Format file size

Convert the size in bytes for a file into a more user-friendly format

<?php

 

    function formatfilesize( $data ) {

    

        // bytes

        if( $data < 1024 ) {

        

            return $data . ” bytes”;

        

        }

        // kilobytes

        else if( $data < 1024000 ) {

        

            return round( ( $data / 1024 ), 1 ) . “k”;

        

        }

        // megabytes

        else {

        

            return round( ( $data / 1024000 ), 1 ) . ” MB”;

        

        }

    

    }

    

?>

 

 


 

 

 

 

 

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: