Log in

View Full Version : Resolved Get database size?



AmenKa
11-10-2008, 08:34 PM
Hey I want to get the size of all of the information in a database, I have this code:

<?php

$db = mysql_connect("server", "username","password"); // Connecting to the server.
mysql_select_db("database",$db); // Specify the database.

function mysql_getDatabaseUsage()
{
$result = mysql_query("SHOW TABLE STATUS"); // Get the table status...
while($row = mysql_fetch_array($result)) // Get each row
{
$total = $row['Data_length'] + $row['Index_length']; // Add Data_length and Index_length
}
return($total); // Return the result in bytes.
}

echo(mysql_getDatabaseUsage()); // Echo the amount of the database used that we are currently connected to in bytes.

mysql_close($db); // Close database connection
?>

That, however, generates this error:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in */mysql.php on line 10

* The long directory to the file...

Any help would be well appreciated!

thetestingsite
11-10-2008, 08:55 PM
on this line:



$result = mysql_query("SHOW TABLE STATUS");


put the following:



$result = mysql_query("SHOW TABLE STATUS") or die('MySQL Error: '.mysql_error());


then post back if you get an error. I think what is happening is that the database connection is not being passed to the function and throwing an error, but I could be wrong.

Hope this helps.

AmenKa
11-11-2008, 01:48 AM
Nice call! I should have tested for a MySQL error myself!

MySQL Error: No database selected

Ok so I adjusted it to properly select the database (entered wrong db)...

Had some issues but I modified it some more to work... I didn't initialize the total to 0 and add each row to it lol... final function:


function mysql_getDatabaseUsage()
{ // Calculates the amount of data in
$sql = "SHOW TABLE STATUS";
$result = mysql_query($sql) or die('MySQL Error: '.mysql_error()); // This is the result of executing the query
$total = 0; // Initialize $total to 0.
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'];
}
$total /= 1024; // Convert from Bytes to KBytes.
$total /= 1024; // KBytes to MBytes
$total = round($total, 1); // Round the total.
return($total); // here we print the file size in bytes
}