mysql_close(): supplied argument is not a valid MySQL-Link resource
Here's what I'm trying to do: I've got a db.php file that does all the db manipulation.
It has 2 static methods, connect and deconnect.
In my other file i simply use db::connect() and db::deconnect(). The mysql_close($con) in the deconnect method just doesn't know who $con is.
Since I don't want to instantiate my class static is the only way to go.
Declaring 'private $con' in class db doesn't seem to have an effect.
Any ideas?
class db {
public static function connect() {
$dbData = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/config.ini');
$con = mysql_connect($dbData['host'],$d开发者_StackOverflow社区bData['user'],$dbData['pass']);
$db = mysql_select_db($dbData['db']);
if ((!$con) || (!$db))
return 0;
else return 1;
}
public static function deconnect() {
mysql_close($con);
}
}
In deconnect
, $con
is out of scope.
You should make it a static member, like this:
class db {
static $con;
public static function connect() {
$dbData = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/config.ini');
self::$con = mysql_connect($dbData['host'],$dbData['user'],$dbData['pass']);
$db = mysql_select_db($dbData['db']);
if ((!self::$con) || (!$db))
return 0;
else return 1;
}
public static function deconnect() {
if( !isset( self::$con ) ) return;
mysql_close( self::$con );
}
}
The message makes sense as $con
is out of scope in your deconnect()
method (deconnect...?).
Use a static data member
class db {
static $con;
}
Access it through self::$con
.
Well, it seems to me that $con is a local variable (local to the method connect). Thus, when you call mysql_close, most likely $con is undefined. Try declaring $con as a private variable in your class. Look here for more info on how to do that.
精彩评论