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

?>


0 Response to Get the size of a MySQL database with PHP

Post a Comment