total mysql rows

Turns out our Mysql server at work is a little bigger than I thought:

Databases 75
Tables    1,549
Rows      1,018,085,348

However over the last couple of months, we’ve only averaged 130 queries/second

Hacked up PHP to gather stats:

class MysqlCounter
{
    public function __construct($host, $username, $password)
    {
        $this->conn = mysql_connect($host, $username, $password, true);
           
        if($this->conn === false)
        {
            throw new Exception("Unable to connect to Mysql server: " . mysql_error());
        }
           
        $this->num_databases = 0;
        $this->num_tables = 0;
        $this->num_rows = 0;
    }
       
    private function query($sql)
    {
        $query = mysql_query($sql, $this->conn);
           
        if($query === false)
        {
            throw new Exception("Unable to run query: $sql\n" . mysql_error($this->conn));
        }
           
        if($query === true)
        {
            return array();
        }
           
        $rows = array();
           
        while ($row = mysql_fetch_array($query))
        {
            $rows[] = $row;
        }
           
        return $rows;
    }
       
    public function gather_stats($callback = false)
    {
        foreach($this->query("SHOW DATABASES") as $row_database)
        {
            $this->num_databases++;
               
            $this->query("USE `{$row_database['Database']}`");
               
            foreach($this->query("SHOW TABLE STATUS") as $row_table)
            {
                $this->num_tables++;
                $this->num_rows += $row_table['Rows'];
                   
                if($callback !== false)
                {
                    $args = array($row_database['Database'], $row_table['Name'], $row_table['Rows']);
                    call_user_func_array($callback, $args);
                }
            }
        }
    }
       
    public static function default_callback($database, $table, $rows)
    {
        printf("%s %s %d\n", $database, $table, $rows);
    }
}

$counter = new MysqlCounter('hostname', 'username', 'password');
$counter->gather_stats(array('MysqlCounter', 'default_callback'));
   
echo "Databases {$counter->num_databases}\n";
echo "Tables    {$counter->num_tables}\n";
echo "Rows      {$counter->num_rows}\n";

This entry was posted on Wednesday, September 9th, 2009 at 11:50 am and is filed under mysql, php, programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply