This is the web log of Tim Bennett, web designer. He also runs Texelate, offering the best web design Leeds, Yorkshire has to offer

Get the size of a MySQL database with PHP

Tuesday, June 27th, 2006 at 8:55 am

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. 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>”;

 

?>

Leave a Reply

You must be logged in to post a comment. If you don't have an account register one now.

Do you need a website or web-related service?
I run an award-winning web design studio.