Oto Shavadze
Oto Shavadze

Reputation: 42753

serialize and then unserialize mysql result object

class a {
  public function getContinents () {
    // connect to db
    $res = $this->db->query("SELECT continent FROM mytable");
    return $res;
  }
}

$obj = new a();
$getContinents = $obj->getContinents();

So if we check variable getContinents here, it is a valid mysqli-result object

var_dump($getContinents);

Result is

object(mysqli_result)#4 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(6) ["type"]=> int(0) }

Now I want to serialize and unserialize this object

$getContinents_to_str = serialize($getContinents);
var_dump(unserialize($getContinents_to_str));

Now result is

Warning: var_dump(): Property access is not allowed yet in ...

object(mysqli_result)#5 (5) { ["current_field"]=> NULL ["field_count"]=> NULL ["lengths"]=> NULL ["num_rows"]=> NULL ["type"]=> NULL }

Please tell me why this happened? Where is it wrong?

Upvotes: 2

Views: 2099

Answers (1)

deceze
deceze

Reputation: 522016

  1. mysqli classes are built in classes which do not necessarily behave the same as your own classes.
  2. A MySQL result set of any kind typically is or contains a resource, a reference to data currently open on the MySQL server. You cannot serialize such external resources, since they're only valid right now, but likely not later.

In short: you cannot serialize a MySQL result set resource.

Upvotes: 6

Related Questions