php - 检查 MySQL 连接 (OOP PHP)

标签 php mysql

我的代码中有多个部分要求我检查是否已建立 mysql 连接。下面我使用的是 if(self::$connection),但是 self::connection 似乎总是返回 "Resource id #6"而不是 bool 值 - 我做错了什么?

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;
    }
...

谢谢!


我的解决方案:断开连接时再次使 $connection 为 false...

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

最佳答案

只需使用 mysql_ping()方法

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
}

关于php - 检查 MySQL 连接 (OOP PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3424655/

相关文章:

mysql - 使用 DataMapper 创建 MySQL 触发器

php - MySQL PDO UNION 查询,查找结果来自的表

MySQL date_add,日期子查询

php - 使用 Xpath 将 href 链接替换为来自同一父节点的字符串

php - 按日期显示数据 mysql

mysql-workbench 不会看到其他客户端所做的数据库更改,除非重新启动连接

c# - 在 Visual Studio 2015 中使用 ADO.NET 和 MySQL

c++ - MySQL 连接器/C++

php - mysqli 查询出现语法错误,但 phpmyadmin 可以工作

php - 如何选择 laravel Controller 以使用 netbeans 进行测试