Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't pass mysqli connection in session in php

I'm trying to pass a session with mysqli connection for multiple queries on the site, but when I try to do a query it outputs a warning "Couldn't fetch mysqli"

$_SESSION['db']=new mysqli($host,$username,$password,$db);

Is it impossible to pass a mysqli connection reference thru session? is there a different method to use?

like image 806
Gal Avatar asked Jan 24 '10 00:01

Gal


3 Answers

Database connections are resources and can't be stored in a session. You'll have to rebuild the connection in every page, or use a persistent connection (PHP 5.3+).

like image 120
Pekka Avatar answered Sep 18 '22 13:09

Pekka


Yes, it is explicitly impossible.

See PHP Documentation here mentioning in a highlighted Warning: "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)."

MySQL connections are one such kind of resource.

You have to reconnect on each page run.

This is not as bad as it sounds if you can rely on connection pooling via mysql_pconnect(), but first see more background info on mysql_pconnect() in this article.

like image 39
Bandi-T Avatar answered Sep 18 '22 13:09

Bandi-T


Yeah - you can't pass it through a session. The handle is specific to the request. You might be able to put it in a shared resource like memcache, and fetch the handle when you need it.

However, if your using connection pooling, grabing a new handle when you need (and closing it when your done) isn't a large performance hit.

Always depends on your needs, but yeah, I'd either:

  • Create a new handle when you need it /per request/ (turn on connection pooling)
  • Stick the dbhandle in memcache
like image 28
mr-sk Avatar answered Sep 19 '22 13:09

mr-sk