Page 1 of 1

Getting mysql_stat info before calling mysql_connect

Posted: Tue Jul 24, 2007 1:34 pm
by anjanesh

Code: Select all

$status = explode('  ',mysql_stat());
$status[1] gives the total number of mysql-threads (mysql connections)

A host like HostGator, allows a maximum of 30 mysql connections at a time per shared account (actually 30 mysql-connections for each mysql-user per shared a/c, so we can have 100 x 30 connections at a time - but in reality its not allowed).

In php.ini, mysql.max_links = -1 so cant rely on that ini_get.

Problem with mysql_stat() is that, it has to be called after a call to mysql_connect().

PHP5:

Code: Select all

$start = microtime(TRUE);
$status = explode('  ', mysql_stat()); # I somehow need this info before doing mysql_connect()
while ($status[1] >= 30) # Host allows only 30 simultaneous connections
 {
        if (microtime(TRUE) - $start > 15) # 15 seconds timeout
         die("Waited too long to get a new connection. Try refreshing the page later.");

        usleep(100);
        $status = explode('  ', mysql_stat());
 }
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
Is there any way I can get this to work ?

At the most I can think of is to have a function like this :

Code: Select all

function mysql_status($h, $u, $p)
 {
        $link = mysql_connect($h, $u, $p);
        $status = explode('  ', mysql_stat($link));
        mysql_close($link);
        return $status;
 }
and do

Code: Select all

$status = mysql_status('localhost', 'mysql_user', 'mysql_password');
But does this really help ?

Thanks

Posted: Tue Jul 24, 2007 2:49 pm
by volka
Just try to connect and check the mysql_errno code.

Posted: Tue Jul 24, 2007 8:42 pm
by anjanesh
mysql_errno will not work because it may actually connect even if its the 31st connection. But we need to limit it to 30.

Posted: Tue Jul 24, 2007 8:53 pm
by Begby
Reserver the 30th connection for getting connection counts. So you will connect, and get the number of active connections. If the connection # is 29 then you are ok, if the connection # is 30, then disconnect. That way you won't go over.