简体   繁体   English

php mysql检查连接是否已建立

[英]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. 这个问题不同于检查我在SO本身和Google搜索结果中找到的特定连接是否存在。

What I want is to check if the mysql connection has already been established. 我想要的是检查是否已建立mysql连接。 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. 我建议使用单例模式和一些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. 您应该使用相同的参数调用mysql_connect 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. 摆脱古老的,已弃用的mysql_扩展是第一步。 Use mysqli or PDO, both of which do not support implicit connections but require you to hand a variable around that represents your connection. 使用mysqli或PDO,它们都不支持隐式连接,但要求您提供代表连接的变量。 That's what you should do anyway for a sane and modular application structure, then you would not have these kinds of questions. 无论如何,对于一个理智的模块化应用程序结构,这应该是你应该做的,那么你就不会有这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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