简体   繁体   中英

php mysql check if connection is already established

This question differs from checking if the specific connection is alive or not which I found in SO itself and in Google Search Resutls.

What I want is to check if the mysql connection has already been established. I need to check this, because I have many modules which needs connection to function. The same module is sometimes called where there is no connection and sometimes called when there is already an connection.

I suggest use singleton pattern and some OO.

class Singleton{
    private static $instance=null;
    public function connection(){
        if(self::$instance==null){
            self::$instance = mysql_connect(); 
    }
        return self::$connection;
    }
}

class TableA extends Singleton{
    function find($id){
        $query="select * from `A` where `id`='$id'";
        mysql_query($query, $this->connection());
        ... // other codes
    }
}

hope that will help you

You should simply call mysql_connect with the same arguments. If an identical connection already exists, it will simply be reused.


That was the lazy answer. Obviously the better way would be to structure your program in a way that you know what your program's status is. Getting rid of the age-old, deprecated mysql_ extension is a first step. Use mysqli or PDO, both of which do not support implicit connections but require you to hand a variable around that represents your connection. That's what you should do anyway for a sane and modular application structure, then you would not have these kinds of questions.

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