简体   繁体   中英

check for MySQL connection (OOP PHP)

I have various parts of my code that require me to check if a mysql connection is already established. Below i'm using if(self::$connection) , but self::connection seems to always return "Resource id #6" rather than boolean - what am i doing wrong?

class mysql_lib{
    static $connection;     

    static function connect($user = FALSE){     
        if(!$user){
            $user = 'mr_update';
        }
        $password = 'some_password';
        self::$connection = mysql_connect('localhost', $user, $password, TRUE);
        mysql_select_db('codlife_headfirst2');      
    }

    static function disconnect(){
        mysql_close(self::$connection);
    }

    static function mres($str){
        if(!self::$connection){
            self::connect('mres');
            $str = mysql_real_escape_string($str);
            mysql_close(self::$connection); 
        }
        else{
            $str = mysql_real_escape_string($str);
        }
        return $str;
    }
...

thanks!


my solution : make $connection false again on disconnection...

static function disconnect(){
    mysql_close(self::$connection);
    self::$connection = FALSE;
}

Just use the mysql_ping() method

Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.

Returns TRUE if the connection to the server MySQL server is working, otherwise FALSE.

static function isActive() {
   return mysql_ping($connection);//returns boolean
}

mysql_connect will return a resource, so that's correct. Don't let that throw you. It looks like everything should work fine. Is there something else not working?

More information:

mysql_connect() returns a MySQL link identifier on success or FALSE on failure. So your $connection variable will be null (which evaluates to false) if no connection attempt has been made. It will be false if a connection attempt was made and failed. If a connection was successfully made, $connection will be a 'MySQL link identifier' which will evaluate to true. If you try to echo or print a 'MySQL link identifier', it will print something like "Resource ID #6". That's what it's supposed to do.

我找到了解决方案,请参阅上面的更新问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM