Is it possible to give a mysql resource to a $_SESSION variable ?
//mysqldb.inc.php
class mySqlDb
{
private $link;
public function __construct($_host = '', $_db = '', $_user = '', $_pwd = '')
{
$link = mysql_pconnect(...);
}
public function query($data)
{
$r = mysql_query($data, $this->link);
return $r;
}
}
//index.php
session_start();
include_once('mysqldb.inc.php');
$sqlobj = new mySqlDb();
$sqlobj->dbconnect($db_host, $db_name, $db_user, $db_pwd);
$_SESSION['mysqldb'] = $sqlobj;
//check.php
session_start();
include_once('mysqldb.inc.php');
$sqlobj = $_SESSION['mysqldb'];
$sqlobj->query(...);
$sqlobj->query(...) return
Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "mySqlDb" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in D:\apache\www\check.php on line 4`
If I use $_SESSION['mysqldb'] = serialize($sqlobj) and $sqlobj = unserialize($_SESSION['mysqldb']) I have this error:
Warning: mysql_query() expects parameter 2 to be resource, integer given in D:\apache\www\mysqldb.inc.php on line ...
解决方案
You cannot persist php resources.
That's it - you just cannot. So you need to connect to database each time.
Because session data is serialized, resource variables cannot be stored in the session.