2

Possible Duplicate:
Can't pass mysqli connection in session in php

I'm trying to store a custom-made PHP MySql class into the $_SESSION. When accessed, PHP throws an error saying: "The script tried to execute a method or access a property of an incomplete object ... ".

include_once 'core/mysql.php';

    $conn = new mysql();
    $_SESSION['DBCONNECTION'] = new mysql();

    $result = $_SESSION['DBCONNECTION']->query_cust($sql);  // Fails!
    $result = $conn->query_cust($sql); // Works!

I'm just tying to understand how the Sessions in PHP work and what makes the difference between defining the class as a normal variable and a variable inside $_SESSION !?

var_dump($_SESSION['DBCONNECTION']) returns:

object(__PHP_Incomplete_Class)[1]
  public '__PHP_Incomplete_Class_Name' => string 'mysql' (length=5)
  public 'con' => int 0
Community
  • 1
  • 1
AlenBer
  • 738
  • 2
  • 8
  • 25
  • You can use var_dump($_SESSION['DBCONNECTION']) to see what the session contain. – zzarbi Dec 11 '11 at 21:59
  • 2
    Apart from the technical difficulty, you shouldn't even do that. It does not belong into a session. Why should each user (=session) have his own database connection handle? – mario Dec 11 '11 at 22:01
  • It eludes me why you would store the database connection in the session. – Till Dec 11 '11 at 22:02
  • Well, how would you do the DB connection handling? Storing the connection as a global? – AlenBer Dec 11 '11 at 22:02
  • 1
    Don't store it at all. Just reconnect with every request and pass the connection to every object that needs it, e.g. via constructor. – middus Dec 11 '11 at 22:04
  • Yes, that is what I have used so far but I thought when I store the initialized connection and just call the query-methods would give me better performance... – AlenBer Dec 11 '11 at 22:07

4 Answers4

6

You cannot store ressource handles within a $_SESSION. See PHP.net:

Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object).

As your object contains the connection link it can't be serialized.

konsolenfreddy
  • 9,551
  • 1
  • 25
  • 36
2

Anything that is stored inside a session needs to be serializable. Why do you want to store the connection inside a session at all? This does not make sense to me. Just reconnect with every request.

middus
  • 9,103
  • 1
  • 31
  • 33
0

Well, several things to comment on

  1. Storing a connection in Session is really bad idea

  2. Storing a resource inside session won't work anyway, AFAIK

  3. As for the internal mechanism, PHP will serialize the object for storing it in session and deserialize it on subsequent request. You should have a look at __sleep and __wakeup magic methods

Tomáš Plešek
  • 1,482
  • 2
  • 12
  • 21
0

When you serialize your mysql class then you can easily sets the object to $_SESSION..

olyanren
  • 1,448
  • 4
  • 24
  • 42