Getting mysql_stat info before calling mysql_connect

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Getting mysql_stat info before calling mysql_connect

Post 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
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Just try to connect and check the mysql_errno code.
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post 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.
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post 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.
Post Reply