本人用了一个类封装mysql_***函数
class MyDB {
private $con = NULL; //数据库连接
private function getConn() {
if (is_null($this->con) == TRUE)
{
$this->con = mysql_connect("127.0.0.1", "root", "123") or die("不能打开连接:". mysql_error());
mysql_query("SET NAMES 'utf8'", $this->con);
mysql_select_db("workspace") or die("数据库不能打开");
}
}
public function execSQL($query) {
$this->getConn();
$res = mysql_query($query, $this->con);
return $res;
}
public function __destruct() {
if (is_null($this->con) == FALSE)
mysql_close($this->con);
$this->con = NULL;
}
//其他成员函数略
}
当在代码写了两次
$obj1 = new MyDB();
$obj1->exexSQL(...);...
$obj2 = new MyDB();
$obj2->exexSQL(...);....
出现Warning: mysql_close(): 13 is not a valid MySQL-Link resource。
在MyDB的析构函数中DEBUG$this->con, 发现
第一个对象析构时:resource(13) of type (mysql link)
第二个对象析构时:resource(13) of type (Unknown)
说明两个MyDB使用了同一个数据连接 resource(13),这都行。
查理php帮助,
原来连续两次mysql_connect的调用时采用相同的数据库连接参数的,将会返回相同的数据库链接。
一个解决方法时 使用mysql_connect 的new_link=TRUE的参数,如: $this->con = mysql_connect("127.0.0.1", "root", "123",TRUE), 其中第4个参数表示每个connect都采用新链接,但这样资源比较浪费,数据库链接不能重用。
一种解决方法,就是用is_resource来判断,即可
public function __destruct()
{
if (is_resource($this->con) == TRUE)
mysql_close($this->con);
$this->con = NULL;
}
此外由于mysql_****函数已经is deprecated as of PHP 5.5.0, and will be removed in the future。所以就改用MySQLi orPDO_MySQL extension为妙!!