2
votes

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

2
I don't see why not. But why would you? - Matt
Also, it may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article. - Matt

2 Answers

4
votes

You cannot persist php resources.

That's it - you just cannot. So you need to connect to database each time.

The $_SESSION documentation notes:

Because session data is serialized, resource variables cannot be stored in the session.

1
votes

You have this:

$sqlobj = new mySqlDb();

But then you do this:

$_SESSION['mysqldb'] = $sql;

I.e. you're setting $_SESSION['mysqldb'] to an object that doesn't exist. Try $sqlobj instead.